public class AppGlobal {
private static Application sApp;
public static Application getApplication() {
if (sApp == null) {
try {
sApp = (Application) Class.forName("android.app.ActivityThread")
.getMethod("currentApplication")
.invoke(null, (Object[]) null);
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassNotFoundException e) {
e.printStackTrace();
}
}
return sApp;
}
}
有些场景下,我们需要获取Application,查看android.app.ActivityThread的源码,
public static Application currentApplication() {
ActivityThread am = currentActivityThread();
return am != null ? am.mInitialApplication : null;
}
我们可以通过反射获取Application