Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Technique for get the ApplicationContext anywhere

Recently I discovered a snippet that use the following technique in order to access statically from anywhere to the application context. It looks cool but is really a nice option or is a bad tech for some reason?

public class MyApp extends Application {
    private static MyApp instance;

    public static MyApp getInstance() {
        return instance;
    }

    public static Context getContext(){
        return instance.getApplicationContext();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }
}
like image 301
Addev Avatar asked Jan 19 '23 04:01

Addev


1 Answers

Unless you simply expose a public method that takes a Context as an argument inside of your classes that require Context (and pass it in from your Activity, etc), this is the way to do it.

like image 83
LuxuryMode Avatar answered Jan 31 '23 03:01

LuxuryMode