GoogleDoc - 温故而知新Activity生命周期方法

3.创建Activity一般人所不知道的地方

  1)Activity里的各个生命周期的方法一般执行什么代码   

  》》onCreate() method shows some code that performs some fundamental setup for the activity, such as declaring the user interface (defined in an XML layout file), defining member variables, and configuring some of the UI.(填充View,定义变量。。。)

   在onCreate()方法里,对于高版本的API,应判断一下系统的的版本再决定是否执行。

// Make sure we‘re running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // For the main activity, make sure the app icon in the action bar
        // does not behave as a button
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(false);
    }

Caution: Using the SDK_INT to prevent older system‘s from executing new APIs works in this way    on Android 2.0 (API level 5) and higher only. Older versions will encounter a runtime exception.

》》onPause()一般与onStop一起执行,应该注意它的特殊情况。

As long as the activity is still partially visible but currently not the activity in focus, it       remains paused.(Activity可见,但是没有获得焦点就会进行pause状态)

As your activity enters the paused state, the system calls theonPause() method on your Activity, which allows you to stop ongoing actions that should not continue while paused (such as a video) or persist any information that should be permanently saved in case the user continues to leave your app. If the user returns to your activity from the paused state, the system resumes it and calls the onResume() method. (在onPause方法里可以停止一些操作,保留信息当用户离开app的时候,当走出paused状态时,Activity会执行onResume方法)

You should usually use the onPause() callback to:

    • Stop animations or other ongoing actions that could consume CPU.(停止动画)
    • Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).
    • Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.(释放网络资源)

Generally, you should not use onPause() to store user changes (such as personal information entered into a form) to permanent storage. The only time you should persist user changes to permanent storage withinonPause() is when you‘re certain users expect the changes to be auto-saved (such as when drafting an email). However, you should avoid performing CPU-intensive work during onPause(), such as writing to a database, because it can slow the visible transition to the next activity (you should instead perform heavy-load shutdown operations during onStop()).

You should keep the amount of operations done in the onPause() method relatively simple in order to allow for a speedy transition to the user‘s next destination if your activity is actually being stopped.

上面的文字中着重强调了,如果想要快速的跳转到下一个Activity,不要将一些重量级的操作放在onPause里,而应该放在onStop方法中。由下图也可以领会这个意思:

Note: When your activity is paused, the Activity instance is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state.

一般初始化相机的方法写在onResume()方法中,release camera的逻辑写在onPause中。

》》onStop() 一般用来释放资源,防止应用线程被杀死。(按下Home键)

When your activity receives a call to the onStop() method, it‘s no longer visible and should release almost all resources that aren‘t needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity‘s final onDestroy() callback, so it‘s important you use onStop() to release resources that might leak memory.

When your activity is stopped, the Activity object is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. The system also keeps track of the current state for each View in the layout, so if the user entered text into an EditText widget, that content is retained so you don‘t need to save and restore it.(Activity stop之前,对象仍然会保存在内存当中,没有必要重新初始化组件了)

Note: Even if the system destroys your activity while it‘s stopped, it still retains the state of the View objects (such as text in an EditText) in a Bundle (a blob of key-value pairs) and restores them if the user navigates back to the same instance of the activity (the next lesson talks more about using a Bundle to save other state data in case your activity is destroyed and recreated).(当Activity stop的时候,即使Activity被销毁了,仍然可以保存View的状态,当用户开启新的Activity实例时会恢复它们)

》》onRestart() 当Activity从stop状态返回到前台时执行这个方法 

When your activity comes back to the foreground from the stopped state, it receives a call to onRestart().The system also calls the onStart() method, which happens every time your activity becomes visible (whether being restarted or created for the first time)

Google重点强调了onRestart与onStart的区别,强烈要求onStart()与onStop配对使用,因为onRestart只有在从stop状态返回的时候被调用,在Activity创建的时候并不会被调用。

theonStart() method is a good place to verify that required system features are enabled:(一般在onStart()方法里进行一些系统特殊是否可用的判断)

2)保存Activity中View的信息

Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).  (比如在切屏的时候,Activity会销毁,但Activity组件数据会消除怎么办?)

Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.(保存View的信息,要求View必须有一唯一的ID值)

具体怎么保存View的状态,View的状态又会传到哪儿去?

To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate()methods.

在代码里保存信息

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first
   
    // Check whether we‘re recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}

取出信息

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);
}
时间: 2024-12-28 07:43:29

GoogleDoc - 温故而知新Activity生命周期方法的相关文章

Activity生命周期方法的调用顺序工程与测试日志

下面为测试activity的方法的执行顺序   工程与测试资源地址 android工程 AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.finalizetest"

Activity生命周期方法的调用顺序project与測试日志

以下为測试activity的方法的运行顺序   project与測试资源地址 androidproject AndroidManifest.xml <? xml version="1.0" encoding="utf-8"? > <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.finali

Android apk动态加载机制的研究(二):资源加载和activity生命周期管理

出处:http://blog.csdn.net/singwhatiwanna/article/details/23387079 (来自singwhatiwanna的csdn博客) 前言 为了更好地阅读本文,你需要先阅读Android apk动态加载机制的研究这篇文章,在此文中,博主分析了Android中apk的动态加载机制,并在文章的最后指出需要解决的两个复杂问题:资源的访问和activity生命周期的管理,而本文将会分析这两个复杂问题的解决方法.需要说明的一点是,我们不可能调起任何一个未安装的

Service的生命周期与Activity生命周期区别

组件的生命周期 应用程序组件都有一个生命周期,从响应Intent的Android实例开始到这个实例被销毁.在这期间,他们或许有效或许无效,有效时或许对用户可见或许不可见.下面我们就来讨论四个基本组件的生命周期,包括在生命周期内的各种状态,以及状态之间的转换.这几种状态可能的结果是:进程让他们停止, 然后实例被销毁.  一.activity生命周期     一个activity有三个基本的状态:  @ 当activity在前台运行时(在activity当前任务的堆栈顶),为活动或者运行状态.这时a

Android学习笔记一:Android基本组件和Activity生命周期

View   View是创建UI的基础控件, Activity  一个应用程序可能包含多个Activity,用来在屏幕中展示用户数据或者编辑用户数据. Fragement  类似于Activity的子控件,一个Activity可以包含一个或多个Fragement. Intent   通常使用Intent来完成以下工作 1.广播消息(Broadcast);2.启动服务(Service):3.启动Activity(Launch Activity):4.显示网页或者联系人列表:5.拨号或者接听电话.

Activity生命周期以及启动模式对生命周期的影响(二)

前面一篇文章概述了Android四大组件之一的Activity生命周期方法的调用先后顺序,但对于非标准启动模式下Activity被多次调用时的一些生命周期方法并未详细阐述,现在针对该情况着重记录. 现象 发布会demo中出现了这样的一种现象:当界面即将出现时,语音重复唤起该界面时,由于在onPause中调用了finish(),界面一直未显示出来,这不是我们想要的. 分析 由于系统组这边存在的一个bug,全屏的Activity出现时会带起在后台运行的应用界面,所以我们这边的Activity不得不采

Android之Activity生命周期详解

Activity的生命周期方法: onCreate()--->onStart()--->onResume()--->onPause()--->onStop()--->onDestory() 单个Activity的三种状态:显示状态,不可见状态,销毁状态.1,activity创建到显示要调用前三个方法.2,点击后退键,做了两件事:(1)当前activity被销毁,调用后面三个周期方法.(2)栈中位于最顶部的Activity显示出来.3,onDestory()方法主要是当Acti

Activity的生命周期方法

简介: Activity类作为Android的系统组件,它由系统创建它的对象, 当这个对象已经创建完成之后,系统会调用一系列指定的方法,这些方法我们 称之为生命周期方法. 什么是生命周期? ·生命周期 是指一个事物(可能是没有实体的)从无到有,然后从有到无 的过程,它的基本意义可以通俗的理解为"从摇篮到坟墓"的整个过程,根据事物不同,经历的阶段所不同. ·Activity是由Android系统进行维护的,它的对象的创建,销毁过程都由Android系统来完成, 并且在创建到销毁的这个阶段

activity生命周期中方法解析

对于activity的生命周期我觉得是一个简单而又不简单的问题,很多人可能觉得自己已经很精通了!往往事实却不以为然! 要接着讨论下面的问题,先来简单了解一下activity,来看一段原文的说明,如下: An activity is a single, focused thing that the user can do.  Almost all activities interact with the user, so the Activity class takes care of creat