如何无依赖地获取Application的Context
发布时间:2020-12-14 02:11:45 所属栏目:百科 来源:网络整理
导读:如何无依赖地获取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
如何无依赖地获取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 {
//1.先获取到当前的ActivityThread对象
Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
//2.获取ActivityTread的静态方法currentApplication
Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentApplication");
//隐藏Api,设置可访问
currentActivityThreadMethod.setAccessible(true);
//3.调用ActivityTread.currentApplication()
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() {
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |