如何无依赖地获取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() {

    }
}

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...