android/底层获取上下文对象

public class ContextUtils {
private static Context applicationContext = null; public static Context getApplicationContext() {
if (null != applicationContext) {
return applicationContext;
} final Object activityThread = getActivityThread();
if (null != activityThread) {
try {
final Method getApplication = activityThread.getClass().getDeclaredMethod("getApplication");
getApplication.setAccessible(true);
applicationContext = (Context) getApplication.invoke(activityThread);
} catch (Exception e) {
e.printStackTrace();
}
} return applicationContext;
}
private static Object getActivityThread() {
try {
final Class<?> clz = Class.forName("android.app.ActivityThread");
final Method method = clz.getDeclaredMethod("currentActivityThread");
method.setAccessible(true);
final Object activityThread = method.invoke(null);
return activityThread;
} catch(Exception e) {
e.printStackTrace();
}
} }
上一篇:程序员必须知道的几个Git代码托管平台


下一篇:Mac OS Sierra安装源不能设置任何来源(anywhere)