天天看點

Android官方入門文檔[14]停止和重新啟動一個Activity活動Android官方入門文檔[14]停止和重新啟動一個Activity活動 Stopping and Restarting an Activity停止和重新啟動一個Activity活動

This lesson teaches you to

1.Stop Your Activity

2.Start/Restart Your Activity

You should also read

•Activities

這節課教你

1.停止您的Activity活動

2.啟動/重新啟動您的Activity活動

你也應該閱讀

•Activity活動

Try it out

Download the demo

ActivityLifecycle.zip

試試吧

下載下傳示範

Properly stopping and restarting your activity is an important process in the activity lifecycle that ensures your users perceive that your app is always alive and doesn't lose their progress. There are a few of key scenarios in which your activity is stopped and restarted:

•The user opens the Recent Apps window and switches from your app to another app. The activity in your app that's currently in the foreground is stopped. If the user returns to your app from the Home screen launcher icon or the Recent Apps window, the activity restarts.

•The user performs an action in your app that starts a new activity. The current activity is stopped when the second activity is created. If the user then presses the Back button, the first activity is restarted.

•The user receives a phone call while using your app on his or her phone.

正确停止和重新啟動Activity活動是在Activity活動周期,以確定您的使用者感覺到你的應用程式始終是活着,不會失去他們的程序的一個重要過程。還有的在您的Activity活動停止和重新啟動的關鍵場景的幾個:

•使用者打開從應用程式最近的視窗和切換你的應用程式到另一個應用程式。在您的應用程式的Activity活動,是目前在前台停止。如果使用者傳回到從主螢幕啟動器圖示或最近的應用程式視窗,該Activity活動将重新啟動您的應用程式。

•使用者在執行您的應用程式啟動一個新的Activity活動的行動。在建立第二activity時,目前Activity活動停止。如果使用者然後按壓後退按鈕時,第一個Activity活動被重新啟動。

•在使用他或她的電話您的應用程式的使用者将收到一個電話。

The Activity class provides two lifecycle methods, onStop() and onRestart(), which allow you to specifically handle how your activity handles being stopped and restarted. Unlike the paused state, which identifies a partial UI obstruction, the stopped state guarantees that the UI is no longer visible and the user's focus is in a separate activity (or an entirely separate app).

Activity類提供了兩個生命周期方法,onStop()和onRestart(),它允許你具體怎麼處理你的activity handlesActivity活動柄被停止和重新啟動。不像暫停狀态,其中确定一個局部的UI阻塞,停止狀态保證在UI不再可見和使用者的焦點是在一個單獨的Activity活動(或完全獨立的應用程式)。

Note: Because the system retains your Activity instance in system memory when it is stopped, it's possible that you don't need to implement the onStop() and onRestart() (or even onStart() methods at all. For most activities that are relatively simple, the activity will stop and restart just fine and you might only need to use onPause() to pause ongoing actions and disconnect from system resources.

注:由于系統保留在系統記憶體中的Activity活動執行個體,當它停止時,它可能是你并不需要實作的onStop()和onRestart()(甚至ONSTART()方法在所有對于大多數Activity活動都是。比較簡單,Activity活動将停止并重新啟動就好了,你可能隻需要使用的onPause()暫停正在采取的行動和從系統資源斷開。

Android官方入門文檔[14]停止和重新啟動一個Activity活動Android官方入門文檔[14]停止和重新啟動一個Activity活動 Stopping and Restarting an Activity停止和重新啟動一個Activity活動

Figure 1. When the user leaves your activity, the system calls onStop() to stop the activity (1). If the user returns while the activity is stopped, the system calls onRestart() (2), quickly followed by onStart() (3) and onResume() (4). Notice that no matter what scenario causes the activity to stop, the system always calls onPause() before calling onStop().

圖1.當使用者離開你的Activity活動時,系統調用的onStop()來停止Activity活動(1)。如果在activity停止使用者傳回,系統調用onRestart()(2),很快接着ONSTART()(3)和onResume()(4)。請注意,無論什麼情況下會導緻Activity活動停止,系統()調用之前一直的onStop調用的onPause()。

--------------------------------------------------------------------------------

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.

當你的Activity活動收到調用的onStop()方法,它不再是可見的,應該釋放被當使用者不使用它并不需要的幾乎所有資源。一旦你的Activity活動停止後,系統可能會破壞例如,如果需要恢複系統記憶體。在極端的情況下,系統可能隻是殺了你的應用程式,而無需調用該Activity活動的最後的onDestroy()回調,讓你用的onStop()來釋放可能洩漏記憶體資源是很重要的。

Although the onPause() method is called before onStop(), you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.

雖然的onPause()方法的onStop()之前調用,你應該使用的onStop()來執行更大,更密集的CPU關機操作,如将資訊寫入資料庫。

For example, here's an implementation of onStop() that saves the contents of a draft note to persistent storage:

例如,這裡的onStop()的實作,儲存一個草案到永久存儲的内容:

@Override

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

            );

}

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活動停止,Activity活動對象保持駐留在記憶體中的Activity活動恢複的時候被調用。你不需要重新初始化過程中的任何的回調方法導緻對已恢複狀态中建立的元件。該系統還跟蹤在每個布局檢視目前的狀态,是以如果使用者輸入的文字變成一個EditText小部件,這些内容被保留,是以你不需要儲存和恢複它。

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活動,而它的停了下來,但仍保留在一個Bundle(鍵值對的BLOB)檢視對象(如一個EditText文本)的狀态,并恢複他們,如果使用者傳回該Activity活動的同一個執行個體(下一課談更多關于使用Bundel捆綁,以節省的情況下你的Activity活動被破壞并重新建立其他狀态資料)。

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). The onRestart() method, however, is called only when the activity resumes from the stopped state, so you can use it to perform special restoration work that might be necessary only if the activity was previously stopped, but not destroyed.

當你的Activity活動回來,從停止狀态的前景,它接收調用onRestart()。該系統還調用ONSTART()方法,這恰好每次你的activity變得可見的時間(無論被重新啟動或首次建立)。該onRestart()方法,但是,被稱為從停止狀态的Activity活動恢複,隻有當,是以你可以用它來執行隻有在以前activity停止,但不被破壞,可能需要特殊的修複工作。

It's uncommon that an app needs to use onRestart() to restore the activity's state, so there aren't any guidelines for this method that apply to the general population of apps. However, because your onStop() method should essentially clean up all your activity's resources, you'll need to re-instantiate them when the activity restarts. Yet, you also need to instantiate them when your activity is created for the first time (when there's no existing instance of the activity). For this reason, you should usually use the onStart() callback method as the counterpart to the onStop() method, because the system calls onStart() both when it creates your activity and when it restarts the activity from the stopped state.

這是罕見的,一個應用程式需要使用onRestart()恢複activity的狀态,是以不會有這種方法适用于應用程式的一般人群的指引。但是,因為你的onStop()方法應該基本上是清理所有activity的資源,你需要重新執行個體化它們的activity重新啟動時。然而,還需要在你的Activity活動是第一次建立執行個體化它們(當有Activity活動的任何現有執行個體)。出于這個原因,你通常應該使用ONSTART()回調方法作為對應到的onStop()方法,因為系統調用ONSTART()都當你建立Activity活動,并在重新啟動時從停止狀态的activity。

For example, because the user might have been away from your app for a long time before coming back it, the onStart() method is a good place to verify that required system features are enabled:

例如,因為使用者可能已經離開你的應用程式很長一段時間回來之前,在ONSTART()方法是一個很好的地方,以驗證功能被啟用所需的系統:

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

    }

protected void onRestart() {

    super.onRestart();  // Always call the superclass method first

    // Activity being restarted from stopped state   

When the system destroys your activity, it calls the onDestroy() method for your Activity. Because you should generally have released most of your resources with onStop(), by the time you receive a call to onDestroy(), there's not much that most apps need to do. This method is your last chance to clean out resources that could lead to a memory leak, so you should be sure that additional threads are destroyed and other long-running actions like method tracing are also stopped.

當系統破壞你的Activity活動,它調用的onDestroy()方法,為您的Activity活動。因為你通常應該已經釋出了你的大部分資源的onStop()的時候,你接到一個電話來的onDestroy(),沒有太多的大多數應用程式需要做的。這種方法是你最後的機會來清理資源,可能導緻記憶體洩漏,是以你應該確定其他線程被破壞和其他長期運作的操作,如方法跟蹤也停止。

Next: Recreating an Activity

下一頁:重新建立一個Activity活動