Android获取全局Context的2种方法
2022-11-26 本文已影响0人
大浪捉鱼
方法一:基于自定义Application
public class MyApplication extends Application {
private static Context instance;
@Override
public void onCreate() {
instance = getApplicationContext();
}
public static Context getContext() {
return instance;
}
}
在AndroidManifest.xml文件的<application>标签下指定:
<application
android:allowBackup="true"
android:icon="@drawable/ista_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name=".ui.MyApplication">
</application>
方法二
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;
}
}