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();

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM