Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Still confusion about Context

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.

like image 820
Android Girl Avatar asked Nov 04 '22 00:11

Android Girl


1 Answers

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:

  1. Creating New objects: Creating new views, adapters, listeners:

    TextView tv = new TextView(getContext()); ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);

  2. Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:

    context.getSystemService(LAYOUT_INFLATER_SERVICE)
    getApplicationContext().getSharedPreferences(name, mode);

  3. 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:

  1. Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
  2. Try using the context-application instead of a context-activity
  3. Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance
  4. A garbage collector is not an insurance against memory leaks
like image 137
K_Anas Avatar answered Nov 09 '22 15:11

K_Anas