0

The following is from this post:

public class MyApp extends android.app.Application {

    private static MyApp instance;

    public MyApp() {
        instance = this;
    }

    public static Context getContext() {
        return instance;
    }

}

But is the context returned by MyApp.getContext() always available? For example, if I call it after a long-running operation... can task killers and other system power saving features kill the application (and its context) completely in the meantime, or will I always have a context to work with by calling MyApp.getContext()?

drmrbrewer
  • 11,491
  • 21
  • 85
  • 181

1 Answers1

1

init instance in onCreate, not in constructor. Do this:

public class MyApp extends android.app.Application {
 override fun onCreate() {
        super.onCreate()
    instance = this

}

  companion object {
        var instance: MyApp? = null
  }
MarfiM
  • 31
  • 2