Saturday, 15 November 2014

Context concept in android.

Context concept in android.

Hi,
I got confused with various way's in android to get the context after doing some home work I found this helpful information. Hope this may help you as well.

The various way's by which we can access the references of context in android is as below.

getApplicationContext(), this, getContext(), getBaseContext() and getApplication() etc.

You also might got confused now. What exactly the difference in the context references returned by above methods. No worry here is the solution for that.

  • this and getContext() both point’s to the current Activity() context and both are same.
  • getApplicationContext() and Activity.getApplication() both return’s the entire application context.
  • getBaseContext() returns the parent context from child context.
O ho! now again the question is Which is the better way to get context reference? and Where to use which type of context?

here is some information you can follow.

Some other tips to better Use of Context.

  • Within an Activity itself, use this for inflating menus, building widgets/dialogs, start other activities, create new Intent within an Activity.
  • In application-wide class, use getApplicationContext() as this context exist for the lifespan of the application.
  • Listener – use a Context substitution like mContext where mContext can be defined as mContext = this;, where this is the context of the current class (Activity, Service, etc).
  • Broadcast Receivers – use the receiver’s own context.
  • Services – use the service’s own context.

Loading...

(Under process will upload All data regards to Android and Java soon)

No comments:

Post a Comment