Android设置全局Context

新建一个java继承Application类

import android.app.Application;
import android.content.Context;

/**
 * 编写自定义Application,管理全局状态信息,比如Context
 * @author autumn
 */
public class MyApplication extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        //获取Context
        context = getApplicationContext();
    }

    //返回
    public static Context getContextObject(){
        return context;
    }
}

在AndroidManifest.xml中注册,在application标签中添加android:name=”com.***.MyApplication”即可

<application
    android:name="com.***.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">
application>

调用获取全局Context

MyApplication.getContextObject();

 

点赞

Leave a Reply

Your email address will not be published. Required fields are marked *