Activity的生命周期
状态:
活动(在屏幕的前面,有焦点并可见)、暂停(失去了焦点,但是它仍然可见)、停止(失去焦点,不可见)、销毁(被系统或进程结束)
过程:
整个完整生命周期:从onCreate()方法到onDestroy()方法结束
可见生命周期:从onStart开始到onStop结束
前台可见生命周期:从onResume()方法到onPause()结束
1、主文件
package com.example.test_activity;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i(TAG, "onDestroy------------------------>");
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i(TAG, "onPause------------------------>");
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.i(TAG, "onRestart------------------------>");
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG, "onResume------------------------>");
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.i(TAG, "onStart------------------------>");
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.i(TAG, "onStop------------------------>");
}
private Button finish;
private static final String TAG = "lifecycle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "onCreate----------------------------->");
finish = (Button) findViewById(R.id.finishiActivty);
finish.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
MainActivity.this.finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
2、主布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity生命周期测试" />
<Button
android:id="@+id/finishiActivty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结束Activity" />
</LinearLayout>
查看log中输出的信息