Possible Duplicate:
Android - what's the difference between the various methods to get a Context?
I want to know what's the difference between using this
, ClassName.this
, getApplicationContext()
or myContext
?
What are the effects of using each as context in the Toast below?
public class ClassName extends Activity {
final ClassName myContext = this;
...
public void onCreate(Bundle savedInstanceState) {
...
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "This is a toast", Toast.LENGTH_LONG).show();
}
});
}
Can you point me to a detailed explanation for contexts? I have read Romain Guy's post here. Maybe a few more examples could help :)
Activity and Application are both derived from the Context class. Therefore,
this
can be used in place of a Context object when your code is part of either an Activity or Application class. Outside of one of these (in a Fragment, for example), you can callgetActivity()
to obtain the enclosing Activity (and use it as a Context). getApplicationContext() is how your Activity gets a Context broader than itself. You might want this if you need to use a Context beyond the lifetime of the Activity where you got it (for example, passing it into a long-running background thread).You probably don't need the Application context in your Toast. But, by using it, your Toast should be able to remain visible and not cause any crashes even if you leave the Activity where you started it.
The application context is tied to the lifecycle of the application, and the Activity Context to the lifecycle of the Activity. So each one has its scope, and have to be used to retreive information at that level.
Normally, you should always use Acitity Context's, unless you need a context whose lifecycle is separate from the current Activity.
What can lead you to memory leaks, is the usage of Application Context, binding it to objects that should be garbage collected, but keeping this relevant attribute (the app context), they are being prevented from being collected.