I am new to android...
Maximum time I have to faced the context
class which sometimes make me confused.
In Some place it use context
,
somewhere it is called by getApplicationContext()
, getContext()
, getBaseContext()
.
I tried to make me understand about it from this site, http://www.developer.android.com/, but it was difficult to understand.
On Android, a Context is used for many operations but mostly to load and access resources. This is why all the widgets receive a Context parameter in their constructor. In a regular Android application, you usually have two kinds of Context, Activity and Application. It's usually the first one that the developer passes to classes and methods that need a Context:
You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).
Typical uses of context:
Creating New objects: Creating new views, adapters, listeners:
TextView tv = new TextView(getContext()); ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:
context.getSystemService(LAYOUT_INFLATER_SERVICE)
getApplicationContext().getSharedPreferences(name, mode);
Accessing Components Implicitly: Regarding content providers, broadcasts, intent
getApplicationContext().getContentResolver().query(uri, ...);
you have to be careful when using context because maintaning it can cause to memory leaks
In summary, to avoid context-related memory leaks, remember the following:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With