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; } } 

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.