Issue
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?
Solution
Very good @CommonsWare's answer... just complementing...
I believe it is a bad solution because it can cause a Memory Leak... Even though it is very very difficult to happen it... to use a static reference to a -- As commented below, it cannot cause any memory leak in this case. Context
instance is very bad because this Application
instance will not be cleaned when ActivityManagerService destroys it due to that static reference...
I don't like this kind of solution... it's safer to use the Context
directly than it (e.g. getApplicationContext()
).
obs.: It is also Violating Singleton Pattern because it is not restricting the instantiation of the class and doesn't ensure that there can be only one instance of it... but it is not relevant...
Answered By - Victor Rattis
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.