How to get Application's Context without dependencies

How to get Application's Context without dependencies


/** * 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() {

    }
}

좋은 웹페이지 즐겨찾기