关于在Android设置全局变量随时获取context

最实在的办法就是继承Application,在里面设置全局变量,因为Application是android的应用入口,并且运行周期贯穿整个程序运行。

import android.app.Application;

public class MyApplication extends Application{
    private static Context mContext;
    
    public static Context getContext (){
        return this.mContext;
    }
    public void setContext (Context mContext){
        this.mContext= c;
    }
    @Override
    public static void onCreate(){
        mContext=this;
        super.onCreate();
    }
}

同时要在AndroidManifest.xml里面的application属性添加android:name=".MyApplication",指明自己定义的application

<application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent" >

 然后在整个程序中,需要context的时候就可以直接调用MyApplication.getContext()进行获取,其他的全局变量也类似。

 

原文地址:https://www.cnblogs.com/wytings/p/4108975.html