如何无依赖地获取Application的Context

前端之家收集整理的这篇文章主要介绍了如何无依赖地获取Application的Context前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

如何无依赖地获取Application的Context


/** * Created by zhangls on 2016/7/6. */
public class ContextProvider {
    private static Context sContext = null;

    /** * Get application context. * * @return */
    public static Context getApplicationContext() {
        if (sContext != null) {
            return sContext;
        }
        try {
            //1.先获取到当前的ActivityThread对象
            Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
            //2.获取ActivityTread的静态方法currentApplication
            Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentApplication");
            //隐藏Api,设置可访问
            currentActivityThreadMethod.setAccessible(true);
            //3.调用ActivityTread.currentApplication()
            Application currentApplication = (Application) currentActivityThreadMethod.invoke(null);
            sContext = currentApplication.getApplicationContext();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        if (sContext == null) {
            throw new NullPointerException("Global application uninitialized");
        }
        return sContext;
    }

    private ContextProvider() {

    }
}
原文链接:https://www.f2er.com/javaschema/283774.html

猜你在找的设计模式相关文章