Android获取全局Context的2种方法

方法一:基于自定义Application

public class MyApplication extends Application {
    private static Context instance;
    @Override
    public void onCreate() {
        instance = getApplicationContext();
    }
    
    public static Context getContext() {
        return instance;
    }
}

在AndroidManifest.xml文件的标签下指定:



方法二

public class ContextUtils {
    /**
     * 获取当前应用的Application
     * 先使用ActivityThread里获取Application的方法,如果没有获取到,
     * 再使用AppGlobals里面的获取Application的方法
     * @return
     */
    public static Application getCurApplication(){
        Application application = null;
        try{
            Class atClass = Class.forName("android.app.ActivityThread");
            Method currentApplicationMethod = atClass.getDeclaredMethod("currentApplication");
            currentApplicationMethod.setAccessible(true);
            application = (Application) currentApplicationMethod.invoke(null);
            Log.d("fw_create","curApp class1:"+application);
        }catch (Exception e){
            Log.d("fw_create","e:"+e.toString());
        }

        if(application != null)
            return application;

        try{
            Class atClass = Class.forName("android.app.AppGlobals");
            Method currentApplicationMethod = atClass.getDeclaredMethod("getInitialApplication");
            currentApplicationMethod.setAccessible(true);
            application = (Application) currentApplicationMethod.invoke(null);
            Log.d("fw_create","curApp class2:"+application);
        }catch (Exception e){
            Log.d("fw_create","e:"+e.toString());
        }

        return application;
    }

}

你可能感兴趣的:(Android获取全局Context的2种方法)