In Android we often have to use Context classes. When a class or method requires a Context we often use Activites or Services for such arguments. The following code is from a website I found but I do not know if this is good practice and if it is okay to use this solution:
public class MyApplication extends Application {
private static MyApplication singleton;
@Override
public void onCreate() {
super.onCreate();
singleton = this;
}
public static MyApplication getInstance() {
return singleton;
}
}
In first place it looks okay to me to use a singleton pattern here. I mean every time some of my app code is executed in Android the system creates a process and therefore also an application context exists which I can use in other classes.
On the other hand it fells wrong to use this. With this pattern every class (also pojo and singletons where we should avoid a Context object) are able to simply get a valid reference to the actual Context which (I think) is not the idea behind the Context object.
So what do you think about this solution? Is it okay to use it or are there some reasons (e.g. lifecycle of application, etc.) to avoid this? Or are some assumptions from me here wrong?