Reputation: 14938
According to this answer or the android's documentation there is several ways to get the Context in an app and pass it to an other class/method/whateveruneed.
Let's say I'm in the Foo Activity and in need to pass the context to Bar's constructor.
Bar bar = new Bar(Foo.this);
Bar bar2 = new Bar(this); //same as first i guess
Bar bar3 = new Bar(getApplicationContext());
Bar bar4 = new Bar(getBaseContext());
Bar bar5 = new Bar(MyApp.getContext); // get context statically
Taking into account of memory leaks, speed , general performance , what will be the better way between all those possibilities ?
Upvotes: 11
Views: 2480
Reputation: 27659
Android memory management. It covers all the aspects of Android memory management.
For context explanation this is a good answer.
Another good explanations of context.
Upvotes: 0
Reputation: 11975
I have not any direct answer to your question.But if you compare Foo.this and this then better to use first one as sometimes (in nested class case) second one will show error.
For more discussion on it go through that link
Using Application context everywhere?.
Hope it will help you
Upvotes: 0
Reputation: 49057
You would probably want to use this. It is the Context of your current Activity (Which is a context) and has shortest lifecycle. But be aware of the memory leak that could occur. http://developer.android.com/resources/articles/avoiding-memory-leaks.html
Upvotes: 0
Reputation: 16570
You should check out this question - which basicly covers the same as yours.
Also the Developer Docs on Avoiding memory leaks gives you a decent explanation of some situtations in which various of the methods are reasonable to use.
Upvotes: 2
Reputation: 4613
I think that this post will provide you enough information. Look at the first response.
Difference between Activity Context and Application Context
Upvotes: 1