直接上代码
方法一:
package cn.xiayiye5.xiayiye5library.utils;
import android.annotation.SuppressLint;
import android.app.Application;
/**
* @author : xiayiye5
* @date : 2021/1/15 18:20
* 类描述 : 通过反射获取全局的application
*/
public class XiaYiYe5Utils {
private static final XiaYiYe5Utils APPLICATION_UTILS = new XiaYiYe5Utils();
private XiaYiYe5Utils() {
}
public static XiaYiYe5Utils getInstance() {
return APPLICATION_UTILS;
}
private Application currentApplication;
/**
* 获取全局的application
*
* @return 返回application
*/
@SuppressLint("PrivateApi")
public Application getNewApplication() {
try {
if (currentApplication == null) {
currentApplication = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null);
}
return currentApplication;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
方法二:请自行验证
import android.app.Application;
/**
* 2018/11/8.
*/
public class EnContext {
private static final Application INSTANCE;
static {
Application app = null;
try {
app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
if (app == null)
throw new IllegalStateException("Static initialization of Applications must be on main thread.");
} catch (final Exception e) {
e.printStackTrace();
try {
app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
} catch (final Exception ex) {
e.printStackTrace();
}
} finally {
INSTANCE = app;
}
}
public static Application get() {
return INSTANCE;
}
}
方法三:原理都是一样的,都是先拿到ActivityThread对象然后调用获取application的方法而已
public class AppKit {
private static Application sApp;
public synchronized static void setApp(Application application) {
sApp = application;
}
public synchronized static Application getApp() {
if (sApp == null) {
sApp = getApplicationWithReflection();
}
return sApp;
}
@SuppressLint("PrivateApi")
private static Application getApplicationWithReflection() {
try {
Method method = Class.forName("android.app.ActivityThread").getMethod("currentActivityThread");
method.setAccessible(true);
Object activityThread = method.invoke(null);
Object app = activityThread.getClass().getMethod("getApplication").invoke(activityThread);
return (Application) app;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}