これの詳細な説明、AndroidのgetContext()、getApplicationContext()、getApplication()、getBaseContext()



Detailed Description This



の種類 意義 備考
この 現在のクラスはコンテキストのサブクラスであり、通常はアクティビティアプリケーションなどです。 1、これは:現在のアクティビティを表します。アクティビティは現在のアクティビティ、つまりアクティビティです。これは、アクティビティではこれと省略できます。
2、Activity.thisコンテキストは、現在のアクティビティのコンテキストを返し、アクティビティに属し、アクティビティは彼を破壊し、破壊します
getContext() getContextは、現在のオブジェクトのコンテキストを取得します
getApplicationContext() 同じコンテキストを取得するには、現在のアプリの任意の場所でこの関数を使用します getApplicationContextを使用して、AndroidManifestで一意に指定されている現在のアプリで使用されているアプリケーションを取得します
getApplication() Android開発におけるグローバルデータの共有
getBaseContext() コンストラクターまたはsetBaseContext()によって指定されたコンテキストを返します

総括する:

1.ダイアログ

ダイアログはアクティビティに依存するため、XXXActivity.thisを直接使用します。アクティビティが消えると、ダイアログは破棄されます。

2.アクティビティ

上ですでに述べたように、現在のアクティビティインスタンスを返すXXXActivity.thisを直接使用します。現在のアクティビティが破棄されると、一緒に破棄されます。



3.service、broadcastReceiver

両方ができます

Summary: It is not recommended to use getApplicationContext() related to UI operation. Generally, the context related to activity is used. The rest of the operations, depending on the specific situation, make a choice according to the length of the existing life cycle. If the UI control needs to use the Activity as the Context object, but the default Toast actually uses the ApplicationContext. In fact, as long as you grasp a point, all related to the UI, you should use Activity as a Context to handle you can see that Activity, Service, Application are subclasses of Context

元のリンク: https://www.xugj520.cn/archives/72.html