在组件化开发过程中难免需要获得主App的application,因为module之间是单向关联的,所以需要通过反射。如下:
private Application fanshe() {
Application application = null;
Class<?> activityThreadClass;
try {
activityThreadClass = Class.forName("android.app.ActivityThread");
final Method method2 = activityThreadClass.getMethod(
"currentActivityThread", new Class[0]);
// 得到当前的ActivityThread对象
Object localObject = method2.invoke(null, (Object[]) null);
final Method method = activityThreadClass
.getMethod("getApplication");
application = (Application) method.invoke(localObject, (Object[]) null);
return application;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
最后我也是做了测试,第一个是主app里打印的,第二个是在副module里面通过反射获取的;地址值是一样的。