LoginSignup
2
2

More than 1 year has passed since last update.

Intentの初期化で渡すContextについて

Posted at

ApplicationContextActivityContextについて調べていると、「IntentActivityContextを渡すと、メモリリークするからよくない」という割と古めの記事を見かけたので、Intentに渡すContextが何をしているのか実際に調べてみました。

val intent = Intent(context, SecondActivity::class.java)
startActivity(intent)

Intentの実装

Android Open Source Project で、Intentのコードを確認しました。

platform_frameworks_base/core/java/android/content/Intent.java
public Intent(Context packageContext, Class<?> cls) {
    mComponent = new ComponentName(packageContext, cls);
}
platform_frameworks_base/core/java/android/content/ComponentName.java
public ComponentName(@NonNull Context pkg, @NonNull Class<?> cls) {
    mPackage = pkg.getPackageName();
    mClass = cls.getName();
}

コードを確認するとわかるように、Contextはパッケージ名(String)を取得する処理に使われています。

Intentで受け取ったContextstaticな変数に保持したりしているわけではないので、Intentに渡すのは、ApplicationContextActivityContextのどちらでも問題なさそうです(ActivityContextを渡すのが普通かな?)

2
2
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
2
2