這是一個認識Android應用程式生命週期的練習.
通過這個練習知道, 原來按下HOME按鈕離開應用程式, 和按下BACK按鈕或調用finish()方法離開應用程式是不相同的.
按下HOME按鈕離開應用程式, 會順序調用: OnPause() -> OnStop().
再次進入應用程式會調用: OnReStart() -> OnStart() -> OnResume().
按下BACK按鈕或調用finish()方法離開應用程式: OnPause() -> OnStop() -> onDestroy().
再次進入應用程式會調用: OnCreate() -> OnStart() -> OnResume().
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/finish"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="exit App by finish()"
/>
</LinearLayout>
主要Java代碼
package com.AndroidLifeCycle;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidLifeCycle extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button finish = (Button)findViewById(R.id.finish);
finish.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}});
Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "onDestroy", Toast.LENGTH_LONG).show();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(this, "onPause", Toast.LENGTH_LONG).show();
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Toast.makeText(this, "onRestart", Toast.LENGTH_LONG).show();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(this, "onResume", Toast.LENGTH_LONG).show();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "onStart", Toast.LENGTH_LONG).show();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(this, "onStop", Toast.LENGTH_LONG).show();
}
}