11

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 ?

Community
  • 1
  • 1
grunk
  • 14,718
  • 15
  • 67
  • 108

5 Answers5

2

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.

Community
  • 1
  • 1
kaspermoerch
  • 16,127
  • 4
  • 44
  • 67
1

I think that this post will provide you enough information. Look at the first response.

Difference between Activity Context and Application Context

Community
  • 1
  • 1
Bram
  • 4,533
  • 6
  • 29
  • 41
0

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.

Community
  • 1
  • 1
Yaqub Ahmad
  • 27,569
  • 23
  • 102
  • 149
0

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

LuckyLuke
  • 47,771
  • 85
  • 270
  • 434
0

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

Community
  • 1
  • 1
Tofeeq Ahmad
  • 11,935
  • 4
  • 61
  • 87