Android学习笔记之全局获取Context

1.因为想要全局都能获取到Context,那么第一个想到的就是Application了,因此我们需要新建一个自定义的Application类去继承Application。

public class MyApplication extends Application

2.然后在其onCreate()的时候去初始化成员变量Context的值,并且提供一个静态方法用来获取Context

public class MyApplication extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }
    public static Context getContext(){
        return context;
    }
}

3.然后在AndroidManifest.xml中注册我们自定义的MyApplication,实际操作是更改application标签的android:name属性的值为自定义类的包名.类名

<application
    android:name="com.xxxx.xxxxx.networktest.MyApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

PS:这里一定要加上完整包名,不然系统将无法找到这个类。

4.最后在需要使用Context的地方通过getContext()方法获取

MyApplication.getContext()

猜你喜欢

转载自blog.csdn.net/Ein3614/article/details/82350060