Android 学习笔记 第五季 6 Activity

来源:互联网 发布:淘宝下载2016官方 编辑:程序博客网 时间:2024/06/10 01:38

第六篇,将介绍下 Activity。


Activity 是 Android 里最常见的一个类。


生命周期

Resumed  正在使用中
Paused      部分可见
Stoped       不可见

Created 和 Started 都是瞬间状态。
在调用 onStop 之前,一定会先调用 onPause。




自动销毁

Android 最大的一个特性就是内存吃紧。
当 Activity 处于 Stoped 状态时,系统可能会为了回收内存,
直接 kill activity 所在的 process。

当然,用户可能会需要重启打开这个 Activity,
这时就要经历 recreate 的过程了。

在系统销毁 Activity 之前,会调用 onSaveInstanceState,可以在这保存一些值。
@Overridepublic void onSaveInstanceState(Bundle savedInstanceState) {    // Save the user's current game state    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);        // Always call the superclass so it can save the view hierarchy state    super.onSaveInstanceState(savedInstanceState);}

而基类的方法已经为我们保存一些值了,比如有 ID 的 View 对象。
然后,在 onRestoreInstanceState 方法中,我们取回保存的值,还原 Activity 之前的状态。

public void onRestoreInstanceState(Bundle savedInstanceState) {    // Always call the superclass so it can restore the view hierarchy    super.onRestoreInstanceState(savedInstanceState);       // Restore state members from saved instance    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);}
这些回调方法可以通过旋转屏幕的方式来测试。


回调函数

在 onPause 中做什么?
Stop animations or other ongoing actions that could consume CPU.
Release system resources that may affect battery life while your activity is paused and the user does not need them.

onPause 应该干很快的活,因为很可能马上就要进入 onStop 了。

在 onStop 中做什么?
释放系统资源。




0 0
原创粉丝点击