Android中Activity生命周期的学习

2014-5-27

1.Activity生命开始

用户在手机里点击应用图标,系统就会调用该应用mainActivity的onCreate(),mainActivity的生命开始。

mainActivity的解释:可以理解为主界面,在manifest中,一个activity的声明中如果有这样一段代码
<activity android:name=".MainActivity" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

那么这个activity就是主界面
所有activity生命都是从onCreate()开始的。

2.下图就是流程图(看了图就一目了然了有木有!!)



3.暂停和恢复Activity

暂停
  举个暂停的例子,就能理解它的意思了:一个半透明的活动打开,以前的活动虽然可见,但是没有获取焦点,那么这个活动就被暂停了。
进入暂停状态,系统调用onPause(),这时候需要把可以保存的数据保存起来,以防用户直接退出。
  官网上说onPause()最好将活动状态调整为一个比较低能耗的状态,怎么理解呢,还是举个例子,如果之前的活动调用了相机,现在活动被暂停了,那么onPause()中最好这么写:
public void onPause() {
    super.onPause();  // Always call the superclass method first

    // Release the Camera because we don't need it when paused
    // and other activities might need to use it
    //.释放相机
    if (mCamera != null) {
        mCamera.release()
        mCamera = null;
    }
}


恢复
  当用户从暂停状态恢复原先的活动,系统调用onResume()方法。
还是用相机的例子,在暂停中相机被释放,恢复的代码中就要:
public void onResume() {
    super.onResume();  // Always call the superclass method first

    // Get the Camera instance as the activity achieves full user focus
    if (mCamera == null) {
        initializeCamera(); // Local method to handle camera init
    }
}


4.onStop()方法,它不再是可见的,应释放被当用户不使用它并不需要的几乎所有资源。一旦你的活动被停止,系统可能会破坏实例,如果需要恢复系统内存。在极端情况下,系统可能会简单地杀死你的应用程序,而不调用活动的最终的onDestroy()回调,所以你使用的onStop()来释放可能泄漏内存资源是很重要的。

5.销毁Activity

OnDestory()方法
大多数情况下不需要去写这个方法,但是如果Activity会影响内存,可以手动销毁Activity
@Override
public void onDestroy() {
    super.onDestroy();  // Always call the superclass
    
    // Stop method tracing that the activity started during onCreate()
    android.os.Debug.stopMethodTracing();
}

猜你喜欢

转载自season-wang.iteye.com/blog/2072380