如何无依赖地获取Application的Context
/** * Created by zhangls on 2016/7/6. */
public class ContextProvider {
private static Context sContext = null;
/** * Get application context. * * @return */
public static Context getApplicationContext() {
if (sContext != null) {
return sContext;
}
try {
Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentApplication");
currentActivityThreadMethod.setAccessible(true);
Application currentApplication = (Application) currentActivityThreadMethod.invoke(null);
sContext = currentApplication.getApplicationContext();
} catch (ClassNotFoundException e) {
e.printstacktrace();
} catch (NoSuchMethodException e) {
e.printstacktrace();
} catch (illegalaccessexception e) {
e.printstacktrace();
} catch (InvocationTargetException e) {
e.printstacktrace();
}
if (sContext == null) {
throw new NullPointerException("Global application uninitialized");
}
return sContext;
}
private ContextProvider() {
}
}