Android开发入门之Activity生命周期

来源:互联网 发布:apache和nginx配合 编辑:程序博客网 时间:2024/04/28 02:31

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";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.i(TAG, "onCreate(Bundle savedInstanceState)");}@Overrideprotected void onStart() {super.onStart();Log.i(TAG, "onStart()");}@Overrideprotected void onRestart() {super.onRestart();Log.i(TAG, "onRestart()");}@Overrideprotected void onResume() {super.onResume();Log.i(TAG, "onResume()");}@Overrideprotected void onPause() {super.onPause();Log.i(TAG, "onPause()");}@Overrideprotected void onStop() {super.onStop();Log.i(TAG, "onStop()");}@Overrideprotected 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()


原创粉丝点击