Wednesday, April 9, 2014

MainActivity.this vs getApplicationContext()

This example examine the behaviour between the contexts retrieved with MainActivity.this vs getApplicationContext(). The getApplicationContext() method return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.

Shown in the following video, MainActivity.this will change when activity destroyed and re-created, getApplicationContext() will change when the application killed and re-started.


MainActivity.java
package com.example.androidtestcontext;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  TextView info1 = (TextView)findViewById(R.id.info1);
  TextView info2 = (TextView)findViewById(R.id.info2);

  String s1 = "MainActivity.this:\n" 
   + "getClass() = " + MainActivity.this.getClass() + "\n"
   + MainActivity.this;
  info1.setText(s1);
  
  String s2 = "getApplicationContext():\n" 
    + "getClass() = " + getApplicationContext().getClass() + "\n"
    + getApplicationContext();
  
  info2.setText(s2);
 }

}

layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/info1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/info2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="italic" />

</LinearLayout>

No comments: