通过反射直接获取Application对象

在Android开发中Context或者Application对象使用是比较多的,在Activity或者Service中可以直接使用this,比较方便。但是如果在其他类中还需要传入Context对象,那么有没有方法可以直接获取Application对象呢?

通过反射方式调用系统方法可以获取:

    public static Application getApplicationByReflection() {
        try {
            return (Application) Class.forName("android.app.ActivityThread")
                    .getMethod("currentApplication").invoke(null, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

查看系统文件ActivityThread.java中的方法,可以看到其中currentApplication()可以获取到当前的Application对象。

通过反射直接获取Application对象_第1张图片

 

你可能感兴趣的:(Android开发)