组件化开发(反射获取主app的application)

在组件化开发过程中难免需要获得主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里面通过反射获取的;地址值是一样的。

在这里插入图片描述
在这里插入图片描述

发布了33 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Zhangyz_521/article/details/89309663
今日推荐