Activity生命周期:
第一步:新建一个Android工程命名为LifeCycle目录结构如下图:
第二步:修改activity_main.xml布局文件代码如下:
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startActivity"
android:text="打开OtherActivity" />
</LinearLayout>
第三步:编写MainActivity类:
package cn.leigo.lifecycle;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate(Bundle savedInstanceState)");
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart()");
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "onRestart()");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause()");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop()");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
public void startActivity(View v) {
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
}
}
第三步:编写OtherActivity类: 通过查看Log可以看到
显示到前台时:
1.按后退键时:
整个生命周期:
onCreate()->onStart()->onResume()->onPause()->onStop()->onDestroy()
2.打开另外一个Activity(完全覆盖MainActivity)时:
整个生命周期:
onCreate()->onStart()->onResume()->onPause()->onStop()->onRestart()->onStart()->onResume()->onPause()->onStop()->onDestroy()
2.打开另外一个Activity(未完全覆盖MainActivity)时:
在AndroidManifest.xml中为OtherActivity配置:
android:theme="@android:style/Theme.Dialog"
整个生命周期:
onCreate()->onStart()->onResume()->onPause()->onResume()->onPause()->onStop()->onDestroy()