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