android studio for android learning (五) 最新Activity理解与其生命周期

来源:互联网 发布:噩梦 知乎 编辑:程序博客网 时间:2024/06/06 15:03

1. Activity是Android程序与用户交互的窗口,是四大组件中最为复杂的一种,需要好好的理解并掌握其生命周期,一个activity的创建和销毁包含很多的回调方法。

2. 一个简化的activity运行图,如下图中所示。

这里写图片描述

一个activity包含创建->开始->继续->暂停->停止->销毁等状态,各个状态间的转化又包含着各种方法,这些方法可以重写或是回调。

activity只有在三个状态下是静态的,就是说只有在这三种状态下可以保存很长的时间。


  • 继续 在这种状态下,Activity处于前台,且用户可以与其交互。(有时也称为“运行”状态。)
  • 暂停 在这种状态下,Activity被在前台中处于半透明状态或者未覆盖整个屏幕的另一个Activity—部分阻挡。 暂停的Activity不会接收用户输入并且无法执行任何代码。
  • 停止 在这种状态下,Activity被完全隐藏并且对用户不可见;它被视为处于后台。 停止时,Activity实例及其诸如成员变量等所有状态信息将保留,但它无法执行任何代码。

记住:其他状态(“创建”和“开始”)是瞬态,系统会通过调用下一个生命周期回调方法从这些状态快速移到下一个状态。 也就是说,在系统调用 onCreate() 之后,它会快速调用 onStart(),紧接着快速调用 onResume()。

AndroidManifest.xml 定义哪个Activity用作主Activity,该说明文件位于您项目目录的根目录中。您的应用的主Activity必须使用 (包括 MAIN 操作和 LAUNCHER 类别)在宣示说明中声明。例如

<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>

3. 实现 onCreate() 方法执行应在Activity整个生命周期出现一次的基本应用启动逻辑。例如, onCreate() 的实现应定义用户界面并且可能实例化某些类范围变量。

TextView mTextView; // Member variable for text view in the layout@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    // 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    mTextView = (TextView) findViewById(R.id.text_message);    // 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);    }}

一旦 onCreate() 完成执行操作,系统会相继调用 onStart() 和 onResume() 方法。 Activity从不会驻留在“已创建”或“已开始”状态。在技术上,Activity会在 onStart() 被调用时变得可见,但紧接着是 onResume(),且Activity保持“继续”状态,直到有事情发生使其发生变化,比如当接听来电时,用户导航至另一个Activity,或设备屏幕关闭。

补充:Bundle主要用于传递数据;它保存的数据,是以key-value(键值对)的形式存在的。还有就是,Bundle是可以对对象进行操作的,而Intent不可以。Bundle相对于Intent比较偏下层,比Intent接口更多,更灵活,但Bundle仍需要借助Intent才能在Activity之间传递。概括一下,Intent旨在数据传递,bundle旨在存取数据,当然intent也提供一部分数据的存取,但比起bundle就显得不专业,不灵活的多。

4.如何销毁activity

@Overridepublic void onDestroy() {    super.onDestroy();  // Always call the superclass    // Stop method tracing that the activity started during onCreate()    android.os.Debug.stopMethodTracing();}

5.暂停和继续activity

什么时候会暂停?前台Activity有时会被其他导致Activity暂停的可视组件阻挡。 例如,当半透明Activity打开时(比如对话框样式中的Activity),上一个Activity会暂停。 只要Activity仍然部分可见但目前又未处于焦点之中,它会一直暂停。

当Activity进入暂停状态时,系统会对 Activity 调用 onPause() 方法,通过该方法,可以停止不应在暂停时继续的进行之中的操作(比如视频)或保留任何应该永久保存的信息,以防用户坚持离开应用。如果用户从暂停状态返回到Activity,系统会重新开始该Activity并调用 onResume() 方法。

这里写图片描述

当半透明Activity阻挡您的Activity时,系统会调用 onPause() 并且Activity会在“暂停”状态下等待 (1)。 如果用户在Activity仍然处于暂停状态时返回Activity,则系统会调用 onResume() (2)。

6. 暂停时,通常应使用 onPause() 回调:

  • 停止动画或其他可能消耗 CPU 的进行之中的操作。
  • 提交未保存的更改,但仅当用户离开时希望永久性保存此类更改(比如电子邮件草稿)。
  • 释放系统资源,比如广播接收器、传感器手柄(比如 GPS) 或当您的Activity暂停且用户不需要它们时仍然可能影响电池寿命的任何其他资源。

例如,如果您的应用使用 Camera, onPause() 方法是释放它的好位置。

@Overridepublic 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;    }}

7. 继续Activity

@Overridepublic 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    }}

8. 几种Activity停止和重新开始的关键场景:

  • 户打开“最近应用”窗口并从您的应用切换到另一个应用。当前位于前台的您的应用中的Activity将停止。 如果用户从主屏幕启动器图标或“最近应用”窗口返回到您的应用,Activity会重新开始。

  • 用户在您的应用中执行开始新Activity的操作。当第二个Activity创建好后,当前Activity便停止。 如果用户之后按了返回按钮,第一个Activity会重新开始。

  • 用户在其手机上使用您的应用的同时接听来电.

这里写图片描述

用户离开Activity时,系统会调用 onStop() 停止Activity(1)。 如果用户在Activity停止时返回,系统会调用 onRestart() (2),紧接着调用 onStart() (3) 和 onResume() (4)。 注意:无论什么场景导致Activity停止,系统始终会在调用 onStop() 之前调用 onPause()。

9.停止Activity

@Overrideprotected void onStop() {    super.onStop();  // Always call the superclass method first    // 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());    getContentResolver().update(            mUri,    // 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.            );}

11. 开始/重新开始Activity

@Overrideprotected void onStart() {    super.onStart();  // Always call the superclass method first    // The activity is either being restarted or started for the first time    // so this is where we should make sure that GPS is enabled    LocationManager locationManager =             (LocationManager) getSystemService(Context.LOCATION_SERVICE);    boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);    if (!gpsEnabled) {        // Create a dialog here that requests the user to enable GPS, and use an intent        // with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action        // to take the user to the Settings screen to enable GPS when they click "OK"    }}@Overrideprotected void onRestart() {    super.onRestart();  // Always call the superclass method first    // Activity being restarted from stopped state    }

12. 每次用户旋转屏幕时,您的Activity将被销毁并重新创建。 当屏幕方向变化时,系统会销毁并重新创建前台Activity,因为屏幕配置已更改并且您的Activity可能需要加载备用资源(比如布局)。

要保存有关Activity状态的其他数据,您必须替代 onSaveInstanceState() 回调方法。当用户要离开Activity并在Activity意外销毁时向其传递将保存的 Bundle 对象时,系统会调用此方法。 如果系统必须稍后重新创建Activity实例,它会将相同的 Bundle 对象同时传递给 onRestoreInstanceState() 和 onCreate() 方法。

这里写图片描述

当系统开始停止您的Activity时,它会 调用 onSaveInstanceState() (1),因此,您可以指定您希望在 Activity 实例必须重新创建时保存的额外状态数据。如果Activity被销毁且必须重新创建相同的实例,系统将在 (1) 中定义的状态数据同时传递给 onCreate() 方法(2) 和 onRestoreInstanceState() 方法(3)。

13. 要保存Activity的更多状态信息,您必须实现 onSaveInstanceState() 并将键值对添加至 Bundle 对象。 例如:

static final String STATE_SCORE = "playerScore";static final String STATE_LEVEL = "playerLevel";...@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);}

14.恢复Activity状态

@Overrideprotected 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    }    ...}

可以选择实现系统在 onStart() 方法之后调用的 onRestoreInstanceState() ,而不是在onCreate() 期间恢复状态。 系统只在存在要恢复的已保存状态时调用 onRestoreInstanceState() ,因此无需检查 Bundle 是否为 null:

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);}
0 0
原创粉丝点击