5

Is it correct to use static method for getting instance of the Application successor in Android. I have seen this approach in a few open source projects: VLC and Shuttle

public class MyApplication extends Application {

    private static MyApplication sApplication;

    public static MyApplication getInstance() {
        return sApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        sApplication = MyApplication.this;
    }

}
Nikola Hristov
  • 686
  • 1
  • 6
  • 11
  • I also do this in my app and it works pretty fine. Basically you can use that instance as long as the app is running. – ulmaxy Apr 11 '17 at 05:13
  • Please define the purpose, then we can guide more into the subject. There is an alternative approach to use dependency injection (DI) such as Dagger is useful in such context. – mpals Apr 11 '17 at 05:19
  • I am going to use this for getting resources, show toasts. I definitely don't want to use Dagger for now. – Nikola Hristov Apr 11 '17 at 05:25

1 Answers1

7

Yes. This approach is correct. This is singleton pattern you are following. As static variable is the right way always, since its the single state you want to maintain everywhere.

Also it is safe, as long as your application never runs in multiple processes. there's a strict one to one ratio of application per process.

I am also using this in my all applications.

Chintan Rathod
  • 25,864
  • 13
  • 83
  • 93