面试—Activity生命周期

activity_lifecycle.png

onCreate()

系统第一次创建Activity时调用,处理Activity整个生命周期仅发生一次的应用初始化操作,例如绑定数据到List中,初始类成员。onCreate()方法接收一个Bundle参数savedInstanceState,保存了Activity之前的状态。如果Activity之前没有被创建过,Bundle是null。

TextView textView;

// some transient state for the activity instance
String gameState;

@Override
public void onCreate(Bundle savedInstanceState) {
    // call the super class onCreate to complete the creation of activity like
    // the view hierarchy
    super.onCreate(savedInstanceState);

    // recovering the instance state
    if (savedInstanceState != null) {
        gameState = savedInstanceState.getString(GAME_STATE_KEY);
    }

    // set the user interface layout for this activity
    // the layout file is defined in the project res/layout/main_activity.xml file
    setContentView(R.layout.main_activity);

    // initialize member TextView so we can manipulate it later
    textView = (TextView) findViewById(R.id.text_view);
}

// This callback is called only when there is a saved instance that is previously saved by using
// onSaveInstanceState(). We restore some state in onCreate(), while we can optionally restore
// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    textView.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}

// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putString(GAME_STATE_KEY, gameState);
    outState.putString(TEXT_VIEW_KEY, textView.getText());

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(outState);
}

onStart()

onStart()让Activity对用户可见

onResume()

进入Resumed 状态时,Activity进入前台,用户与Activity交互(interacts )。Activity一直保持在这个状态直到失去焦点(比如接入电话、跳转到另一个Activity、设备屏幕关闭)

当阻碍事件发生时,activity 进入 Paused state,系统触发onPause()方法。

当Activity从Paused state 返回到Resumed state,系统会再次调用onResume()。因此在onResume()的初始化操作,在onPause()要释放掉。

onPause()

当用户离开Activity的时候调用(这并不意味着Activity被销毁),这说明Activity不再处于前台(尽管它仍然保持可见在multi-window mode)。一些让Activity进入 paused state的例子:
1.一些事件打断了App的运行,如在onResume()部分提到的例子。这是最常见的。
2.在 Android 7.0版本以上, 在multi-window 模式下运行多个App,因为只能由一个App获得焦点,系统让其他App处于paused状态。
3.一个新的,半透明的Activity打开(如Dialog)。尽管Activity部分可见但没有焦点,处于paused 状态。

在onPause()里可停止任何非前台状态不需要的功能,如停止相机预览。

在onPause()释放系统资源,处理 sensors(像GPS),或者任何影响电池续航的。

onPause()执行时间非常短,没有提供足够的时间去处理保存操作,因此,不要在这里保存应用或用户数据、调用网络、或执行数据库操作,类似的工作在onPause()方法结束前不能完成。这些可以在onStop()方法调用。

onStop()

当Acivity对用户不再可见时,进入了Stopped state,系统回调onStop()。当一个新启动的Activity覆盖了整个屏幕,会触发。 当Activity结束运行时也会触发。

在onStop()可以释放掉当Activity不可见时不需要的资源。例如停止动画、将定位更新从fine-grained切换到coarse-grained。

@Override
protected void onStop() {
    // call the superclass method first
    super.onStop();

    // save the note's current draft, because the activity is stopping
    // and we want to be sure the current note progress isn't lost.
    ContentValues values = new ContentValues();
    values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
    values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());

    // do this update in background on an AsyncQueryHandler or equivalent
    asyncQueryHandler.startUpdate (
            mToken,  // int token to correlate calls
            null,    // cookie, not used here
            uri,    // The URI for the note to update.
            values,  // The map of column names and new values to apply to them.
            null,    // No SELECT criteria are used.
            null     // No WHERE columns are used.
    );
}

当activity 进入 Stopped state , activity对象还保留在内存中, 它保存所有状态和成员信息,但是没绑定到window manager。当Activity resume,activity恢复这些信息。系统同时追踪每个View对象的状态,因此EditText输入的文本依然会保存,你不需要再去保存和恢复。

Activity从stopped state返回与用户交互,会调用onRestart()。如果结束Activity会调用onDestroy()。

onDestroy()

activity 被销毁前调用onDestroy()。下面情况会触发:

1.Acitvity正在结束(用户退出Activity,或者调用finish())

2.系统因为configuration 改变 (如设备旋转或者multi-window mode)临时销毁Activity

在onDestroy()需要释放在早期生命周期没有释放掉的资源。

当 Activity A 启动 Activity B 时生命周期的变化

  1. Activity A 的 onPause()方法执行。
    2.Activity B 的 onCreate()、onStart()、onResume()方法依次执行(Activity B获得焦点)
    3.Activity A 不再可见,它的onStop()方法执行。
    (如果Activity B是一个半透明的Dialog,则Activity A只执行onPause(),onStop()不会执行)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容