您的位置:首页 > 移动开发 > Android开发

Android 之 Activity Life Cycle

2010-10-18 18:06 295 查看
声明:本人博客纯属个人学习过程中的一些仿写的简单练习记录,其他论坛也有类似内容!(可能不免有错误之处,还望见谅,指出)

这个程序解析了Activity整个生命周期,把TAG标识复写父类方法的Log通过打印展示出来;程序里面加入
了一个EditText,目的在于体现:一个Activity从启动到停止但还未销毁(比如按了设备上的home键),即只执行了onCreate、onStart、onResume、onPause、onStop;待重启此Activity时,即执行了onRestart、onStart、onResume,还能保持切换之前的状态。

首先创建项目名为:LifeCycle
具体代码如下:

package com.demo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;

public class LifeCycle extends Activity {
private static final String TAG = "Activity"; 给定义的字符串变量赋值
private String text;
private EditText edittext; //构造一个编辑框对象
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittext = (EditText)findViewById(R.id.editText1); //联系到视图布局
Log.i(TAG, "=========================================================onCreate");
}
protected void onStart(){
super.onStart();
Log.i(TAG, "=========================================================onStart");
}
protected void onRestart(){
super.onRestart();
edittext.setTextKeepState(text); //通过这个方法可以保存切换Activity之前的输入内容
Log.i(TAG, "=========================================================onRestart");
}
protected void onResume(){
super.onResume();
Log.i(TAG, "=========================================================onResume");
}
protected void onPause(){
super.onPause();
text = edittext.getText().toString(); //得到输入的内容
Log.i(TAG, "=========================================================onPause");
}
protected void onStop(){
super.onStop();
Log.i(TAG, "=========================================================onStop");
}
protected void onDestroy(){
super.onDestroy(); //程序执行onDestroy这个方法说明Activity彻底结束
Log.i(TAG, "=========================================================onDestroy");
}
}

视图布局文件 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="wrap_content"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<EditText android:layout_height="wrap_content"
android:layout_width="fill_parent" android:id="@+id/editText1" />
</LinearLayout>

Activity显示内容如图:



对应打印台的日志如图:



当输入文字后按下home键后打印台日志如下:



之后再次启动次程序则打印:



若要彻底退出程序按BACK键回到首页则会打印:



这就说明Activity已彻底销毁!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: