Lifecycle Code Example for Android – onCreate(), onPause(), onResume()

In Android lifecycle, methods are automatically called. This simple example toasts a message each time this happens.
Create a new project SimpleStuff, package com.botbook.simplestuff. Run your program and see the states change. Press home button to stop the program. Hold down home button and select your program to get back to running state.
Prequisites: Android SDK installation, Android Hello World explained

Lifecycle Code Example

package com.botbook.simplestuff;
// Copyright 2011 Tero Karvinen http://terokarvinen.com/tag/android
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;
public class SimpleStuffActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tToast("onCreate");
    }
    public void onStart() {
    	super.onStart();
    	tToast("onStart");
    }
    public void onRestart() {
    	super.onRestart();
    	tToast("onRestart");
    }
    public void onResume() {
    	super.onResume();
    	tToast("onResume");
    }
    public void onPause() {
    	super.onPause();
    	tToast("onPause: bye bye!");
    }
    public void onStop() {
    	super.onStop();
    	tToast("onStop.");
    }
    public void onDestroy() {
    	super.onStop();
    	tToast("onDestroy.");
    }
    private void tToast(String s) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, s, duration);
        toast.show();
    }
}

See also:

Android Reference: Activity

Posted in Uncategorized | Tagged , , , | 1 Comment

One Response to Lifecycle Code Example for Android – onCreate(), onPause(), onResume()