Activity Lifecycle

Entire Lifetime:  This is the lifetime between the first call to the onCreate() and the final call to onDestroy()method. We create all global resources such as screen layout, global variables etc in onCreate() and release all resources with onDestroy() call.

 

Visible Lifetime:  It is the lifetime of an Activity between onStart() and onStop() method calls. In this the Activity is visible to the user and he may or may not be able to interact with it. During the visible lifetime, an Activity maintains its state intact.

 

Foreground Lifetime:  Foreground lifetime starts with onResume() and ends with onPause() method calls. During this, the Activity is completely visible to the user and is on top of all other Activities so that user can interact with it.

[Source: http://www.android-app-market.com/android-activity-lifecycle.html%5D

___________________________________________________________________________________________

onCreate()

Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity’s previously frozen state, if there was one. Always followed by onStart().

onStart()

Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden. onStart() method is called before the Activity is being visible to the User. Activity is still not Active.

onResume()

Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause(). With the onResume() method, the Activity become visible and Active for the user to interact with. The Activity will be at the top of the Activity stack at this point. Now the Activity is in running /active state and is able to receive user inputs.

Activities should override this method to perform tasks such as:

  • Ramping up frame rates (a common task in game building)
  • Starting animations
  • Listening for GPS updates
  • Display any relevant alerts or dialogs
  • Wire up external event handlers

onPause()

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().

  • In the Active state, onPause() method will be called when the system is about to resume another Activity on top of this one or when the user is about to navigate to some other other parts of the system. It is the last guaranteed call to a method before the Activity  can get killed by the system. That is, there’s a possibility that your activity may be killed by the system at the paused state without executing any further method calls. Therefore it is important to save the user interface configuration and critical data at this method.
  • By default, an Activity can remain in the paused state if:
  • The user has pressed the home button
  • Another activity or notification which is on top of it doesn’t completely obscures the visibility of underlying Activity.
  • The device goes to sleep.
  • There are three possibilities for an Activity under paused state:
  1. The user resumes the Activity by closing the new Activity or notification and the paused Activity gets Active/Running by calling onResume()
  2. It gets killed by the system under extremely low memory conditions. In this case there will be no further method calls before the destruction of the Activity and it needs to be re-run from the beginning by calling onCreate() and restoring the previous configuration from bundle object.

In all other cases it goes to stopped state by executing onStop() method. This is the default action when the user has pressed the back button, or a new activity which completely covers it resumes on top.

Activities should override this method if they need to:

  • Commit unsaved changes to persistent data
  • Destroy or clean up other objects consuming resources
  • Ramp down frame rates and pausing animations
  • Unregister external event handlers or notification handlers (i.e. those that are tied to a service). This must be done to prevent Activity memory leaks.
  • Likewise, if the Activity has displayed any dialogs or alerts, they must be cleaned up with the.Dismiss() method.

OnStop()

Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity’s process running after its onPause() method is called.

  • An Activity under stopped state also has three different scenarios to happen:
  1. System kills it to free resources. An activity under stopped sate is more likely to be killed by the system than one in the paused state. It needs to start the cycle again with onCreate().
  2. It get restarted by calling onRestart()onStart() and onResume() methods in the order if the user navigates back to the Activity again. In this case, the User Interface is intact and no need to be restored.
  3. onDestroy() method is called and the Activity is destroyed. This is the final method we can call before the Activity is destroyed. This occurs either because the Activity is finishing the operation or the system is temporarily destroying it to save space.

onDestroy()

The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

 

When the Activity first time loads the events are called as below:

onCreate()

onStart()

onResume()

When you click on Phone button the Activity goes to the background and the below events are called:

onPause()

onStop()

Exit the phone dialer and the below events will be called:

onRestart()

onStart()

onResume()

When you click the back button OR try to finish() the activity the events are called as below:

onPause()

onStop()

onDestroy()

[Source : http://stackoverflow.com/questions/8515936/android-activity-life-cycle-what-are-all-these-methods-for

http://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/%5D

 

 

 

 

Live Folder Example : Getting Saved Contacts to livefolder

Following Example Demonstrates how to create Live Folder and getting contacts to this live foler.

Live Folder is useful in many ways you can bring live RSSFeed and any Builtin / custom content provider
data to live folder

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

LiveFolderActivity.java

package com.example.livefolder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.provider.LiveFolders;
import android.view.Menu;

public class MainActivity extends Activity {

	//public static final Uri CONTENT_URI = Uri.parse("content://contacts/");
	public static final Uri CONTENT_URI = People.CONTENT_URI;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final Intent intent = getIntent();
        final String action = intent.getAction();

        if (LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals(action)) {
            setResult(RESULT_OK, createLiveFolder(getApplicationContext(), CONTENT_URI,
                    "Contacts", R.drawable.ic_launcher));
        } else {
            setResult(RESULT_CANCELED);
        }

        finish();
    }

    private static Intent createLiveFolder(Context context, Uri uri, String name, int icon) {
        final Intent intent = new Intent();

        intent.setData(uri);
        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME, name);
        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON,
                Intent.ShortcutIconResource.fromContext(context, icon));
        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST);

        return intent;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
}

AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.livefolder"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.livefolder.MainActivity"
            android:label="@string/app_name" >
                <intent-filter>
             <action android:name="android.intent.action.CREATE_LIVE_FOLDER"/>
             <category android:name="android.intent.category.DEFAULT" />
       </intent-filter>
            
                    </activity>
    </application>

</manifest>

LiveFolder1

LiveFolder2

LiveFolder3

LiveFolder4

Insert, Update and Delete Contact Using ContentProvider

Following Code demonstrates insert, update and delete contact using Content provider

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView1"
        android:layout_toLeftOf="@+id/imageView1"
        android:text="Button" />

</RelativeLayout>

ContactIUD.java

package com.example.contactscp5a;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	Cursor c;
	int count=0;
	Uri u,pu;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		createContact("mca5a","1111");
		
		Button b = (Button)findViewById(R.id.button1);
		b.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
                                  createContact("ASDFG");
				//deleteContact("ASDFG");
				//updateContact("pqr");
			}
		});
		
	}
	private void updateContact(String nm)
	{
		ContentValues cv = new ContentValues();
		//cv.put(People.NAME, "mca5a");
		cv.put(People.Phones.TYPE, People.TYPE_HOME);
		cv.put(People.NUMBER, "89898");
	//	Cursor c = managedQuery(People.CONTENT_URI, new String[]{People.NAME}, People.NAME+"=?", new String[]{nm}, null);
		//Toast.makeText(getApplicationContext(), c.getCount()+"", 50).show();
		getContentResolver().update(pu, cv, 
				null,null);
	}
	private void createContact(String nm,String phno)
	{
		ContentValues cv = new ContentValues();
		cv.put(People.NAME, nm);
		u = getContentResolver().insert(People.CONTENT_URI, cv);
		pu = Uri.withAppendedPath(u, People.Phones.CONTENT_DIRECTORY);
		cv.clear();
		cv.put(People.Phones.TYPE, People.TYPE_MOBILE);
		cv.put(People.NUMBER,phno);
		u = getContentResolver().insert(pu, cv);
	}
	private void deleteContact(String nm)
	{
		getContentResolver().delete(People.CONTENT_URI, 
				People.NAME+"=?", new String[]{nm});
		////getContentResolver().delete(u, null, null);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}