0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

applicationContext と this の違いついて

0
Posted at

結論

this                → 今のActivityのContext
applicationContext  → アプリ全体のContext

早速ですが、簡単にいうと上記のようになります。
ここから先では、もう少し詳しく違いを解説していきます。

Contextってそもそも何?

  • リソースへアクセスするための窓口
  • システムサービスを取得するためのもの
  • Activity / Service / Application が持っている
    Contextについてはこの3点を押さえておけばいいと思います。

this とは何か?

Activity内での

this

MainActivity.this

と同じです。
つまり、今表示されている画面(Activity)のContext

例:

AlertDialog.Builder(this)
startActivity(Intent(this, SubActivity::class.java))

特徴としては、以下です。

  • ライフサイクルはActivityと同じ
  • 画面が消えると一緒に破棄される
  • UIに紐づく処理に使う

applicationContext とは何?

一言で言うと、アプリ全体で1つだけ存在するContextです。
特徴としては、以下の3点で

  • アプリ終了まで生き続ける
  • Activityに依存しない
  • UI操作には基本使わない

例:

applicationContext.getSharedPreferences(...)

メモリリークについて

良くない例としてこのようなものがあります。

object SampleManager {
    var context: Context? = null
}
SampleManager.context = this

SampleManager はアプリが終了するまで生き続けるのに対して、this(Activity) を入れている状態になります。これをやると、本来消えるはずの画面が終わっても、Activityが参照が残る状態になってしまいます。
もう使わないのに、メモリに残り続ける不要なもの つまりメモリーリークに繋がってしまいます。

まとめ

Contextは「とりあえずthis」で書いてしまいがちですが、
ライフサイクルを理解して使い分けないとメモリリークの原因になります。
特にSingletonやManagerクラスではapplicationContextを使うように気をつけたいですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?