前端之家收集整理的这篇文章主要介绍了
如何无依赖地获取Application的Context,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何无依赖地获取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() {
}
}
原文链接:https://www.f2er.com/javaschema/283774.html