Android-多线程下任意位置获取应用Context

2017-11-26  本文已影响0人  滴沥的雨云
 public static Application getApplication() {
        if (Looper.getMainLooper() != Looper.myLooper()) {
            final Object obj = new Object();
            final Application[] res = {null};
            synchronized (obj) {
                try {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            res[0] = getApplication();
                            obj.notify();
                        }
                    });
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return res[0];
        }
        try {
            return (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            return (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
注意:

建议不要用反射,比较耗时,可以在application的onCreate中存一个静态变量

参考:http://www.jianshu.com/p/808b9d92d6cd

上一篇下一篇

猜你喜欢

热点阅读