'Is the Context returned from Application the same as getApplicationContext()?
The following is based on this post with one added function getAppContext():
public class MyApp extends android.app.Application {
private static MyApp instance;
public MyApp() {
instance = this;
}
public static Context getContext() {
return instance;
}
public static Context getAppContext() {
return instance.getApplicationContext();
}
}
But is there any difference between the context returned by getContext() and getAppContext()? And is it the same context that is returned by getApplicationContext() within an Activity or elsewhere? Are they all what is referred to as the "application context"?
Solution 1:[1]
public class MyApp extends android.app.Application {
override fun onCreate() {
super.onCreate()
instance = this
}
companion object {
var instance: MyApp? = null
}
class MainActivity :
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val isSame = TheApplication.instance == applicationContext
Log.e(
TAG,
"onCreate: $isSame, " +
"TheApplication.instance: ${TheApplication.instance}, " +
"applicationContext: ${applicationContext}"
)
}
}
Result :
MainActivity: onCreate: true,
TheApplication.instance: com.example.MyApp@6a56b6,
applicationContext: com.example.MyApp@6a56b6
Yes, they are the same objects.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MarfiM |
