• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
lamber
博客园    首页    新随笔       管理    订阅  订阅

Android 之 Activity Life Cycle

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


这个程序解析了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已彻底销毁!

想要获得成功,首先要自己相信自己,再者要赢得周围朋友的信任!
posted @ 2010-10-18 18:06  android5k  阅读(1875)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3