4

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;
    }
}
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Addev
  • 28,535
  • 43
  • 166
  • 288

2 Answers2

5

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.

LuxuryMode
  • 31,806
  • 34
  • 112
  • 184
4

This will certainly work. Just be careful as with using any singleton that you don't abuse it. Read the answer to this question explaining why the ApplicationContext is rarely (though sometimes) the right Context to use.

Also, having the ApplicationContext available everywhere allows you to be more sloppy with how you organize your classes since you won't need to think about what functionality really needs the ApplicationContext and whether you should factor that out, etc. That's just a maybe depending on how disciplined you are.

I'm always pretty wary of singletons although other notable people disagree, but I think it's still fairly widely debated whether singletons are a pattern or anti-pattern. If you Google singleton and anti-pattern you'll find articles like this which make some fairly good points in my opinion.

Community
  • 1
  • 1
kabuko
  • 35,009
  • 7
  • 75
  • 92