0

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"?

drmrbrewer
  • 11,491
  • 21
  • 85
  • 181
  • You can try it yourself. From inside an Activity lifecycle call `System.out.format("Context equals? %s", getApplicationContext().equals(MyApp.getContext())).flush();` – PPartisan Apr 21 '22 at 07:44

1 Answers1

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

MarfiM
  • 31
  • 2