[Kotlin]アプリケーションコンテキストの入手方法


アプリケーションクラス
≪アプリケーション|Application|emdw≫:アプリケーションの実行時に最初に実行されます.インスタンスは1つだけです.
Application Context:アプリケーションの実行中にメンテナンスを行い、クラス後の実行時のみ変更します.
getApplicationContext():アプリケーションのグローバルステータス情報を返す
アプリケーションの継承
import android.app.Application;
import android.content.Context;

public class MainApplication extends Application {
    private static Context applicationContext;
    
    public static Context getAppContext() {
        return applicationContext;
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        applicationContext = getApplicationContext();
    }
}
  • MainApplication.java
  • アプリケーションContext:静的と宣言し、現在実行中のアプリケーションContextをバインドします.
  • onCreate():アプリケーションが最初に実行されたときに呼び出されます.
  • MainApplicationの呼び出し
    AndroidManifest.xmlは明示的な設定が必要です.
    <application
    	android:name=".MainApplication"
        ...
    </application>
  • 関数:MainApplicationを呼び出します.getAppContext()
  • リファレンス
  • Android Kotlinアプリケーションプログラミングガイド