Technique to get ApplicationContext anywhere

I recently discovered a fragment that uses the following method to access statically from anywhere in the application context. It looks cool, but a really nice option, or for some reason technically bad?

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; } } 
+4
source share
2 answers

Unless you just publish a public method that takes Context as an argument inside your classes, which requires Context (and pass it from your Activity , etc.), this is the way to do it.

+5
source

This will certainly work. Just be careful how to use any singleton that you do not abuse it. Read the answer to this question , explaining why ApplicationContext rarely (though sometimes) uses the appropriate context.

In addition, having an ApplicationContext available everywhere allows you to be more careless about how you organize your classes, since you won’t need to think about what functionality the ApplicationContext really needs, and whether you should take this into account, etc. It is just possible, depending on how disciplined you are.

I am always very careful in singles, although other famous people do not agree, but I think it is still quite widely discussed whether singletones are a pattern or an anti-pattern. If you use the singleton and Google anti-pattern, you will find articles like this that, in my opinion, make some good points.

+4
source

Source: https://habr.com/ru/post/1382956/


All Articles