Activities活動

Activities活動

An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map.html

一個Activity是一個應用組件,它提供了一個屏幕,用戶經過此屏幕進行交互操做,並處理一些事情,好比像拔電話,拍照,發郵件,看地圖。java

Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.每一個acivity是一個窗口,能夠在上面畫用戶的界面。通常窗口填充整個屏幕,但也可能比屏幕小,並浮於其餘窗口上面.linux

An application usually consists of multiple activities that are loosely bound to each other. 一個應用一般由多個activities組成,它們鬆散的邦定在一塊兒。android

Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. 通常,一個應用中指定個activity看成"主"activity,當運行該應用時,它首先呈現給用戶ios

Each activity can then start another activity in order to perform different actions.爲了執行不一樣的activtiy,每一個activity能夠啓動另外一個activity.數據庫

Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack").windows

每次一個新的activity開始,選前的activity被中止,可是系統保留這個activity在一個堆中(返回堆)數組

When a new activity starts, it is pushed onto the back stack and takes user focus. 當一個新的activity開始時,它被壓入到返回堆上,並獲取用戶的焦點網絡

The back stack abides to the basic "last in, first out" queue mechanism, so, when the user is done with the current activity and presses the BACK key, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in the Tasks and Back Stack document.)session

返回堆,遵循「後進,先出」的規則,因此當用處理完當前的activity並按返回鍵,當前的activity從返回堆上彈出(而且銷燬)而且前一個activity恢復。(Tasks and Back Stack文檔中有更多討論。)

When an activity is stopped because a new activity starts, it is notified of this change in state through the activity's lifecycle callback methods.

當一個activity因爲一個新的activity啓動而中止時,會經過activity的生命週期回調方法來通知這種狀態的改變

There are several callback methods that an activity might receive, due to a change in its state—whether the system is creating it, stopping it, resuming it, or destroying it—and each callback provides you the opportunity to perform specific work that's appropriate to that state change.

一個activity有好幾個用於接收的回調方法,這是因爲它的改變的狀態---是否系統正在建立它,中止它,恢復它,和銷燬它---而且每一個回調方法提供一個機會,讓你根據相應的狀態的改變,來作一些特定的工做。

For instance, when stopped, your activity should release any large objects, such as network or database connections. When the activity resumes, you can reacquire the necessary resources and resume actions that were interrupted.

好比,當中止時,你的activity應釋聽任何的大對象,好比網絡或者數據庫鏈接。當一個activity恢復時,你能夠從新請求必要的資源並恢復被中斷的操做。

These state transitions are all part of the activity lifecycle.這些都是生命週期轉換的一部分

The rest of this document discusses the basics of how to build and use an activity, including a complete discussion of how the activity lifecycle works, so you can properly manage the transition between various activity states.

本文檔的下面部分,討論怎麼去構建和使用activity的的基礎,包括徹底討論activity的生命週期是如何工做的,以便你能相應的管理activity狀態的轉換

Creating an Activity建立一個activity

To create an activity, you must create a subclass of Activity (or an existing subclass of it).

要建立一個活動,你必須建立一個Activity子類(或一個已存在的它的子類)

In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed. The two most important callback methods are:

在你的子類中,你須要實現回調方法,當活動轉換它的生命週期的各類狀態時(好比當活動被建立,中止,恢得或銷燬),系統將調用這些回調方法,下面是兩個最重要的回調方法:

onCreate()You must implement this method. The system calls this when creating your activity.你必須實現這個方法,當建立你的活動時,系統將調用它。 Within your implementation, you should initialize the essential components of your activity.在你的實現中,你應該初始化你的活動的關鍵的組件。 Most importantly, this is where you must call setContentView() to define the layout for the activity's user interface.最重要的是,你必須在這裏調用 setContentView()方法指定用戶界面的佈局。 onPause()The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed). 用戶正在離開你的活動時,系統首先調用這個方法,(但這並老是表示活動正在被銷燬)This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back). 這裏經常是你提交那些須要永久保存的改變的地方(由於用戶可能會返回來).

There are several other lifecycle callback methods that you should use in order to provide a fluid user experience between activities and handle unexpected interuptions that cause your activity to be stopped and even destroyed. 爲了給用戶提供流暢的體驗,你須要用到其餘幾個生命週期回調方法,並處理致使你的活動中止甚至銷燬的意想不到中斷

All of the lifecycle callback methods are discussed later, in the section about Managing the Activity Lifecycle.全部回調方法,在後面的中Managing the Activity Lifecycle討論

Implementing a user interface實現用戶界面

The user interface for an activity is provided by a hierarchy of views—objects derived from the View class.

一個活動的用戶界面,是經過view的層級來提供的--從View類衍生出來的對象.

Each view controls a particular rectangular space within the activity's window and can respond to user interaction.

每一個view控制一個方形空間,這裏面是一個activity窗口,並能響應用戶的交互操做。

For example, a view might be a button that initiates an action when the user touches it.好比,一個view多是一個按鈕,當用戶觸模它時,觸發一個動做。

Android provides a number of ready-made views that you can use to design and organize your layout.

Adnroid提供了大量的準備好的views,你能夠用來設計和組織你的佈局。

"Widgets" are views that provide a visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image.

"Widgets"是一些views,它提供爲屏幕提供可視元素,好比一個按鈕,文本區,複選框,或只是圖片。

"Layouts" are views derived from ViewGroup that provide a unique layout model for its child views, such as a linear layout, a grid layout, or relative layout.

"Layouts"是一些views,它從 ViewGroup中衍出來,爲它的子views提供一個惟一的佈局模型,好比線性佈局,網格佈局,或相對佈局。

You can also subclass the View and ViewGroup classes (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.

你能夠從ViewViewGroup中(或存在的子類)擴展出子類;來建立你本身的widgets和layouts,並應用到你的activity佈局中。

The most common way to define a layout using views is with an XML layout file saved in your application resources.

一般是用一個XML佈局文件,定義你的視圖佈局,保存在你的應用資源中。

This way, you can maintain the design of your user interface separately from the source code that defines the activity's behavior.

這樣,你能將用戶界面的設計與定義activity的行爲的代碼分開。

You can set the layout as the UI for your activity with setContentView(), passing the resource ID for the layout. 你能夠傳一個佈局的資源ID,給setContentView()方法,經過此方法把佈局變成你的activity的UI(用戶界面)

However, you can also create new Views in your activity code and build a view hierarchy by inserting new Views into a ViewGroup, then use that layout by passing the root ViewGroup to setContentView().

而後,你也能夠用activity代碼,建立新的視圖View,而且經過將View插入到ViewGroup中,構建新的視圖層次.而後,把佈局根ViewGroup傳給setContentView()

For information about creating a user interface, see the User Interface documentation.關於建立用戶界面,請看User Interface文檔

Declaring the activity in the manifest在manifest中聲明activity

You must declare your activity in the manifest file in order for it to be accessible to the system. 爲了讓系統能訪問你的activity,你必須在manifest中聲明它。

To declare your activity, open your manifest file and add an <activity> element as a child of the <application> element. For example:

要聲明你的activity,打開manifest文件,加入一個<application>元素的<activity>子元素。例如

<manifest ... >
  <application ... >
      <activity android:name=".ExampleActivity" />
      ...
  </application ... >
  ...
</manifest >

There are several other attributes that you can include in this element, to define properties such as the label for the activity, an icon for the activity, or a theme to style the activity's UI. 在這個元素中,你能夠包括一些其餘的元素,來定義屬性,好比活動的 label,icon,或者activity的UI主題風格.

The android:name attribute is the only required attribute—it specifies the class name of the activity.

android:name屬性,是惟一必須有的屬性—它指定了活動的類名.

Once you publish your application, you should not change this name, because if you do, you might break some functionality, such as application shortcuts (read the blog post, Things That Cannot Change).一旦發佈了你的應用,你應不要改變這個名字,由於若是你這樣作的話,可能會破壞一些功能。好比像應用的快捷鍵(讀取博客)

See the <activity> element reference for more information about declaring your activity in the manifest.更多關於在manifest中聲明activity的引用,請看<activity>元素.

Using intent filters使用意圖過濾器

An <activity> element can also specify various intent filters—using the <intent-filter> element—in order to declare how other application components may activate it.一個<activity>元素也可以使用各類意圖過濾器——經過使用<intent-filter>元素——爲了聲明其餘應用組件是如何激活它。

When you create a new application using the Android SDK tools,當你用SDK工具建立一個新的應用,

the stub activity that's created for you automatically includes an intent filter that declares the activity responds to the "main" action and should be placed in the "launcher" category. The intent filter looks like this:

將自動爲你建立stub activity,包含了一個意圖過濾器,它聲明瞭這個activity響應"main"動做,而且應該放在"lanucher"中.

<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

The <action> element specifies that this is the "main" entry point to the application. <action>元素指定了這是應用的主要("main")入點

The <category> element specifies that this activity should be listed in the system's application launcher (to allow users to launch this activity).

元素指示,這個activity應該列在系統的應用laucher中(運行器)(以容許用戶運行這個activity).

If you intend for your application to be self-contained and not allow other applications to activate its activities, then you don't need any other intent filters.

若是你想讓你的應用是獨立的(self_contained)並不讓其餘的應用激活它的活動,那麼你不須要任何其也的意圖過濾器。

Only one activity should have the "main" action and "launcher" category, as in the previous example. 就如前面的例子,應只有一個活動有"main"動做和"launcher"。

Activities that you don't want to make available to other applications should have no intent filters and you can start them yourself using explicit intents (as discussed in the following section).你不想讓其餘應用訪問的活動,應該不要有意圖過濾器,而且你可使用顯式的意圖來聲明它(後面將討論)

However, if you want your activity to respond to implicit intents that are delivered from other applications (and your own), then you must define additional intent filters for your activity. 然而,你想讓你活動響應來自其餘應用發出的隱式意圖,那麼你必須爲你的活動定義另外的意圖過濾器。

For each type of intent to which you want to respond, you must include an <intent-filter> that includes an <action> element and, optionally, a <category> element and/or a <data> element. 對於每一個你想要響應的意圖類型,你必須包含一個包含了<action>元素的<intent-filter>。可選的,一個<category>元素和/或者<data>元素

These elements specify the type of intent to which your activity can respond.這些元素指出了你的活動能響應的意圖類型。

For more information about how your activities can respond to intents, see the Intents and Intent Filters document.更多關於你的activities能響應的intents,看Intents and Intent Filters文檔。

Starting an Activity啓動一個活動

You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start. 你能夠調用傳一個IntentstartActivity()方法,啓動另外一個activity,在Intent中描述你想要啓動的activity.

The intent specifies either the exact activity you want to start or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application). 這個intent,要麼描述你想要啓動的activity,要麼描述你想要執行的動做類型(而且系統爲你選一個相應的活動,這個活動能夠是其餘應用的活動。)

An intent can also carry small amounts of data to be used by the activity that is started.一個意圖也能夠攜帶小量的數據,給那個要啓動的activity使用.

When working within your own application, you'll often need to simply launch a known activity. 在你的應用中,你將常常須要只是簡單的運行一個已知的活動

You can do so by creating an intent that explicitly defines the activity you want to start, using the class name. 你能夠這樣作,建立一個意圖,並在其中用類名指定你想要啓動的活動。

For example, here's how one activity starts another activity named SignInActivity:好比,這裏是一個活動怎樣啓動一個叫作的SignInActivity活動的例子。

Intent intent = new Intent(this, SignInActivity.class);//指定類名的方法
startActivity(intent);

However, your application might also want to perform some action, such as send an email, text message, or status update, using data from your activity.

然而,你的應用可能也想執行一些動做,好比,發送一個郵件,文本消息或更新狀態,使用來自你活動的數據。

In this case, your application might not have its own activities to perform such actions, so you can instead leverage the activities provided by other applications on the device, which can perform the actions for you.

這種狀況下,你的應用可能沒有執行該動做的活動,因此你能夠藉助設備中其餘應用提供的活動,讓它來爲你執行該動做。

This is where intents are really valuable—you can create an intent that describes an action you want to perform and the system launches the appropriate activity from another application.

這纔是意圖真正的價值體現——你能夠建立一個意圖,在乎圖中描述你想要執行的一個動做,而且系統能從其餘的應用中運行合適的活動。

If there are multiple activities that can handle the intent, then the user can select which one to use. For example, if you want to allow the user to send an email message, you can create the following intent:

若是有多個活動能處理這個意圖,那麼用戶能夠從中選一個。好比,你想容許用戶發送一個email消息,你能夠建立這樣一個間圖

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
startActivity(intent);

The EXTRA_EMAIL extra added to the intent is a string array of email addresses to which the email should be sent.

這個EXTRA_EMAIL加入意圖的是,要發送到的email地址數組。(recipientArray:即接收郵件的郵件地址數組)

When an email application responds to this intent, it reads the string array provided in the extra and places them in the "to" field of the email composition form.

當一個email應用,響應了這個intent,它讀取在extra中提供的字串數組,並把它們放到電子郵件表的"to"的域。

In this situation, the email application's activity starts and when the user is done, your activity resumes.

在這種狀況下, email應用的activity啓動了,並當用戶完成操做時,你的活動會恢復。

Starting an activity for a result啓動一個帶有返回結果的活動

Sometimes, you might want to receive a result from the activity that you start. 有時候,你可能想從你啓動的活動中收到一個結果。

In that case, start the activity by calling startActivityForResult() (instead of startActivity()).

在那種狀況下,調用startActivityForResult()這個方法啓動活動(面不是startActivity()方法)

To then receive the result from the subsequent activity, implement the onActivityResult() callback method.

而後,實現onActivityResult()回調方法爲了接收來自後續活動的結果,

When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.

當後續的活動完成操做,它在Intent中返回一個結果給你的onActivityResult()方法。

For example, perhaps you want the user to pick one of their contacts, so your activity can do something with the information in that contact. Here's how you can create such an intent and handle the result:

好比,也許你想要用戶從它們的通訊錄中,選取一個,以便你的活動能夠對其作些處理,下面是你如何建立這樣一個意圖,並處理返回結果的例子 。

private void pickContact() {//選取一個通訊項
    // Create an intent to "pick" a contact, as defined by the content provider URI
    Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
    startActivityForResult(intent, PICK_CONTACT_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {//這裏是對返回結果的處理方法
    // If the request went well (OK) and the request was PICK_CONTACT_REQUEST
    if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
        // Perform a query to the contact's content provider for the contact's name
        Cursor cursor = getContentResolver().query(data.getData(),
        new String[] {Contacts.DISPLAY_NAME}, null, null, null);
        if (cursor.moveToFirst()) { // True if the cursor is not empty
            int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
            String name = cursor.getString(columnIndex);
            // Do something with the selected contact's name...
        }
    }
}

This example shows the basic logic you should use in your onActivityResult() method in order to handle an activity result.

這個例子只是展現了,爲了處理一個activity結果,在你的onActivityResult()方法中應使用的基本邏輯.

The first condition checks whether the request was successful—if it was, then the resultCode will be RESULT_OK

第一個條件檢查請求是否成功——若是是,那麼resultCode將是RESULT_OK

—and whether the request to which this result is responding is known—in this case, the requestCode matches the second parameter sent with startActivityForResult().

而且,檢查請求響應的這個結果是不是已知的——在這個例子中,requestCode匹配第二個參數,它是從startActivityForResult()發出的

From there, the code handles the activity result by querying the data returned in an Intent (the data parameter).

從這裏,代碼經過查詢Intent中(數據參數)返回的數據,處理活動的返回結果。

What happens is, a ContentResolver performs a query against a content provider, which returns a Cursor that allows the queried data to be read. For more information, see the Content Providers document.

發生的事情是:一個ContentResolver執行對內容提供者的查詢,這樣返回一個Cursor,它(Cursor)能使得數據能夠被讀取,更多詳細信息看文檔

For more information about using intents, see the Intents and Intent Filters document.更多關於intent使用的信息,請看Intents and Intent Filters文檔。

Shutting Down an Activity 關閉一個Activity

You can shut down an activity by calling its finish() method. You can also shut down a separate activity that you previously started by calling finishActivity().

調用finish()方法,你能關閉一個活動,你也能夠調用finishActivity()方法,關閉你先前開啓的一個獨立的活動

Note: In most cases, you should not explicitly finish an activity using these methods. As discussed in the following section about the activity lifecycle, the Android system manages the life of an activity for you, so you do not need to finish your own activities. Calling these methods could adversely affect the expected user experience and should only be used when you absolutely do not want the user to return to this instance of the activity.

注意:在大多數狀況下,你不該顯示的用這些方法結束一個活動,像下面部分關於活動的生命週期的討論 ,Android系統爲你管理活動的生命週期,因此不須要本身關閉活動的生命週期,調用這些方法可能對用戶體驗有不利的影響,而且應該只用於,當你肯定不想讓用戶返回到那個活動的實例時的狀況。

Managing the Activity Lifecycle管理生命週期

Managing the lifecycle of your activities by implementing callback methods is crucial to developing a strong and flexible application.

經過實再回調方法管理你的活動的生命週期,對於開發強健靈活的應用很是關鍵。

The lifecycle of an activity is directly affected by its association with other activities, its task and back stack.

一個活動的生命週期直接影響與其關聯的其餘活動,它的堆和返回堆

An activity can exist in essentially three states:一個活動有三個關鍵的狀態。

Resumed恢復The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)       活動進入屏幕前臺,並捅有用戶焦點(這個狀態有時候也便是「running」運行態)
Paused暫停Another activity is in the foreground and has focus, but this one is still visible. 另外一個活動進入前臺,並捅有焦點,但這個活動仍然可見That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen.  那是指,另外一個活動出如今本活動的上面,而且部分是透明的,或者沒有徹底覆蓋整個屏幕。A paused activity is completely alive (the Activity object is retained in memory, it maintains all state and member information, and remains attached to the window manager), but can be killed by the system in extremely low memory situations.g 一個暫停的活動是徹底是有生命的,(這個對象仍駐留在內存中,它維持着全部的狀態和內存信息,並關聯到窗口管理器)但在內存至關有限的狀況能夠殺掉。
Stopped中止狀態The activity is completely obscured by another activity (the activity is now in the "background").這個activity徹底被另外一個activity所湮沒(這個activity如今是在"後臺") A stopped activity is also still alive (the Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager). 箇中止的活動還是有生命的,(這個對象仍駐留在內存中,它維持着全部的狀態和內存信息,但不關聯到窗口管理器) However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere. 然而,它對用戶再也不可見,在當其餘的地方須要內存時,系統能夠殺掉它。

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish() method), or simply killing its process.

若是一個活動暫停或者停時了,系統經過要求它完成(調用finish()方法),或簡單的殺掉它的進程,來把它從內存中移除。

When the activity is opened again (after being finished or killed), it must be created all over.當再次打開時(在結束或殺掉後),它必須所有從新建立

Implementing the lifecycle callbacks實現生命週迴調方法

When an activity transitions into and out of the different states described above, it is notified through various callback methods.

當一個活動在上述各類不一樣的狀態來回轉換時,它是經過回調方法被通知到的。

All of the callback methods are hooks that you can override to do appropriate work when the state of your activity changes.

當你的活動改變狀態時,全部的回調方法都是勾子函數,你能夠複寫它來作相應的工做。

The following skeleton activity includes each of the fundamental lifecycle methods:下面這個骨架活動包括了每一個生命週期的基本方法

public class ExampleActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.
    }
    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
}

Note: Your implementation of these lifecycle methods must always call the superclass implementation before doing any work, as shown in the examples above.

注意:你的生命週期方法的實現,必須總在作任何其餘工做以前,調用超類的實現,就像上面例子所展現的.(注意註釋行與超類方法的前後位置)

Taken together, these methods define the entire lifecycle of an activity. By implementing these methods, you can monitor three nested loops in the activity lifecycle:

總之,這些方法定義的活動整個生命週期,經過實現這些方法,你能監視活動生命週期的三個嵌套循環。

  • The entire lifetime of an activity happens between the call to onCreate() and the call to onDestroy().
  • 活動的完整的生命時間發生在調用onCreate(),onDestroy()兩個函數之間.
  • Your activity should perform setup of "global" state (such as defining layout) in onCreate(), and release all remaining resources in onDestroy().
  • 你的活動應在onCreate()這個方法中執行設置全局狀態(好比定義佈局),並在onDestroy()方法中釋放全部的駐留資源
  • For example, if your activity has a thread running in the background to download data from the network, it might create that thread in onCreate() and then stop the thread in onDestroy().
  • 好比,若是你的活動有一個線程運行在後臺下載網上的數據,它可能在onCreate()方法建立一個線程,而且在onDestroy()這個方法中止它
  • The visible lifetime of an activity happens between the call to onStart() and the call to onStop().

  • 一個活的可見的生命時間,發生在調用onStart()和調用onStop()方法之間

    During this time, the user can see the activity on-screen and interact with it. 在這段時間內,用戶能夠在屏幕上看到活動並能與它交互。

  • For example, onStop() is called when a new activity starts and this one is no longer visible.

  • 好比,當一個新的活動開啓,onStop()方法被調用,這個活動將再也不可見

  • Between these two methods, you can maintain resources that are needed to show the activity to the user.

  • 在這兩個方法之間,你能夠維持活動須要顯示給用戶的資源

  • For example, you can register a BroadcastReceiver in onStart() to monitor changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying.

  • 好比,你能夠在onStart()中註冊一個BroadcastReceiver,來監視影響你的UI的改變,當用戶再也不須要看你的顯示時在onStop()中註銷它。
  • The system might call onStart() and onStop() multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.

  • 當活動交替着對用戶顯示或隱藏時,系統可能在活動的整個生命時間之間,屢次調用onStart()onStop()這兩個方法。

  • The foreground lifetime of an activity happens between the call to onResume() and the call to onPause().

  • 活動的前臺生命時間,發生在調用onResume()和調onPause()方法之間
  • During this time, the activity is in front of all other activities on screen and has user input focus.

  • 在這段時間內,這個activity在屏幕上的全部其餘活動上,而且捅有用戶輸入焦點
  • An activity can frequently transition in and out of the foreground—一個活動可能常常在先後以前轉換(進入並退出前臺)

  • for example, onPause() is called when the device goes to sleep or when a dialog appears.

  • 好比,當設備進入睡眠或當一個對話框出現了,onPause()被調用

  • Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.

  • 由於這個狀態常常轉換,因此在這兩個方法中的代碼應該是輕量級的,以免由於轉換慢而致使用戶須要等待。

Figure 1 illustrates these loops and the paths an activity might take between states. The rectangles represent the callback methods you can implement to perform operations when the activity transitions between states.

圖1說明了活動在狀態之間發生轉換時的循環和路徑,矩形表示回調方法,當活動在狀態之間轉換時,你能夠實現它執行一些操做

activity_lifecycle

Figure 1. The activity lifecycle.活動的生命週期

The same lifecycle callback methods are listed in table 1, 表格1列出的是相同的生命週期回調方法

which describes each of the callback methods in more detail and locates each one within the activity's overall lifecycle, including whether the system can kill the activity after the callback method completes.它詳細的描述了每一個回調方法,及它在每一個活動的生命週期內的定位,包括在回調方法調後完成後,系統是否能殺掉它。

Table 1. A summary of the activity lifecycle's callback methods.活動生命週期回調方法的總結

Method
Description
Killable after?
Next
onCreate()

Called when the activity is first created. This is where you should do all of your normal static set up — create views, bind data to lists, and so on. This method is passed a Bundle object containing the activity's previous state, if that state was captured (see Saving Activity State, later).

Always followed by onStart().

當活動第一次被建立時調用,在這裏你應處理全部的靜態設置——建立視圖,邦定數據到列表,等等,這個方法被傳入一個Bundle對象,它包含了活動以前的狀態,是否狀態被捕獲(看後面的Saving Activity State)老是跟着onStart().方法

No onStart()
onRestart()

Called after the activity has been stopped, just prior to it being started again.

Always followed by onStart()

當活動中止後調用,只是優先於再次啓動以前,老是跟着onStart()方法

No
onStart()
onStart()

Called just before the activity becomes visible to the user.

Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

當活動變成對用戶可見以前調用,若是活動來自前景跟隨着onResume()方法,或者變成隱藏時跟着onStop()方法

No
onResume()
or
onStop()
onResume()

Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it.

Always followed by onPause().

只是在活動開始與用戶交互以前調用,在這時,活動處理活動堆的頂部,用戶輸入給它。老是跟着onPause()暫停方法(理解:系統在調用這個方法以後,隨後離開時首先調的是暫停方法)

No
onPause()
onPause()

Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns.

Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.

當系統將要恢復其餘的活動時調用,這個方法主要是用於提交沒有保存的永久數據的改變,入中止動畫和其餘可能消CPU的東西,等等。它應快速處理要作事情,由於下一個活動直到它返回後才能恢復。若是活動從後臺到前臺跟隨着onResume()恢復方法,若是變得對用戶不可見了,跟隨一個onStop()中止方法

Yes
onResume()
or
onStop()
onStop()

Called when the activity is no longer visible to the user. This may happen because it is being destroyed, or because another activity (either an existing one or a new one) has been resumed and is covering it.

Followed either by onRestart() if the activity is coming back to interact with the user, or by onDestroy() if this activity is going away.

當活動對用戶再也不可見時調用,當發生這處調用時,可能活動正在被銷燬,或者另外一個活動(一個存在的或一個新的)被恢復,並正在覆蓋它。若是活動即將與用戶交互跟onRestart()一個方法,這個活動正在離開跟一個 onDestroy()方法 .

Yes
onRestart()
or
onDestroy()
onDestroy()
Called before the activity is destroyed. This is the final call that the activity will receive. It could be called either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
在活動被銷燬以前,這是活動將要接收到的最後一個調用。它被調用多是因爲活動正在完成,或者因爲系統要保留空間,正在臨時性的銷燬它。你能夠用isFinishing()這個方法來區分這兩種狀況
Yes
nothing

 

The column labeled "Killable after?" indicates whether or not the system can kill the process hosting the activity at any time after the method returns, without executing another line of the activity's code.

標有"Killable after?"的列,指示在這些方法調用返回後,系統是否能殺掉捅用該activity的進程,而不執行活動代碼的其餘行。

Three methods are marked "yes": (onPause(), onStop(), and onDestroy()). 三個方法被標記了"yes": (onPause(), onStop(), and onDestroy()).

Because onPause() is the first of the three, once the activity is created,因爲onPause() 方法是三個中的第一個( 難以理解這句話的要表達什麼),一旦活動被建立

 onPause() is the last method that's guaranteed to be called before the process can be killed—if the system must recover memory in an emergency,

在進程被kill前,onPause()方法是最後個保證會被調用的方法---若是系統在緊急狀況下必須回收內存時

then onStop() and onDestroy() might not be called. 而後是onStop()onDestroy()方法可能不會被調用到

Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage.所以,你應該用onPause()方法去把一些關鍵數據寫到存儲器中

However, you should be selective about what information must be retained during onPause(), 可是,在onPause()方法中,你應該選擇性保存那些必需要記住的的信息

because any blocking procedures in this method block the transition to the next activity and slow the user experience.

由於這個方法中的任何的阻塞過程,阻止轉換到下一個活動,並所以下降了用戶的體驗

Methods that are marked "No" in the Killable column protect the process hosting the activity from being killed from the moment they are called.

Killable 列,標記爲」No」的方法,從它們被調用的那一刻開始,保護持有將被殺活動的進程,

Thus, an activity is killable from the time onPause() returns to the time onResume() is called.

所以,一個活動在onPause()方法那一刻,到返回onResume()方法被調用那一刻之間,是能夠被殺掉的.

It will not again be killable until onPause() is again called and returns. 直到onPause()方法再次被調用和返回以前,它將不能再次被殺掉

Note: An activity that's not technically "killable" by this definition in table 1 在表1中定義的,一個活動不是技術上的」能夠殺掉(killable)」,

might still be killed by the system—but that would happen only in extreme circumstances when there is no other recourse.

當沒有資源時,可能仍被系統殺掉---但只會在極端的狀況下發生這種狀況.

When an activity might be killed is discussed more in the Processes and Threading document.

Processes and Threading 文檔中,更詳細的討論了,關於一個活動何時可能被殺掉。

Saving activity state保存活動狀態

The introduction to Managing the Activity Lifecycle briefly mentions that when an activity is paused or stopped, the state of the activity is retained.

Managing the Activity Lifecycle介紹中,簡單的說起了,當一個活動被暫停或中止時,活動的狀態仍駐留.

This is true because the Activity object is still held in memory when it is paused or stopped—all information about its members and current state is still alive.

這是真的,由於當Activity對象被暫停或中止時,它仍駐留在內存---全部它的成員和當前狀態信息還是活的(alive).

Thus, any changes the user made within the activity are retained in memory, 所以,用戶對活動的任何改變被駐留在內存中.

so that when the activity returns to the foreground (when it "resumes"), those changes are still there.因此當該活動返回到前臺(當它被恢復」resume」)時,這些改變仍在那兒。

 

Figure 2. The two ways in which an activity returns to user focus with its state intact: 圖中有兩種方法,一個活動帶着它原有的狀態返回到用戶焦點。

either the activity is stopped, then resumed and the activity state remains intact (left), 要麼活動被中止,而後恢復,該活動的狀態恢復原樣(左圖)

or the activity is destroyed, then recreated and the activity must restore the previous activity state (right).或者活動被銷燬,而後從新建立,而且該活動必須從新恢復先前的活動狀態

However, when the system destroys an activity in order to recover memory, the Activity object is destroyed, so the system cannot simply resume it with its state intact.

但,當系統爲了回收內存,而銷燬了一個活動,這個Activity對象被銷燬了,因此係統不能簡單的恢復它原有的狀態。

Instead, the system must recreate the Activity object if the user navigates back to it. 而是,若是用戶導航返回它時,系統必須從新建立Activity對象.

Yet, the user is unaware that the system destroyed the activity and recreated it and, 但時,用戶不能察着到,系統銷燬了活動並重建立了它,

thus, probably expects the activity to be exactly as it was. In this situation, 而且正由於感着不到這些,因此可能期活動能跟原來同樣。在這種狀況下

you can ensure that important information about the activity state is preserved

by implementing an additional callback method that allows you to save information about the state of your activity and then restore it when the the system recreates the activity.

你能夠經過實現一個附加的方法,它能容許你保存你活動的狀態信息,而後當系統重建立活動時而且能恢復活動的狀態,以確保你的活動的重要信息被保存了.

The callback method in which you can save information about the current state of your activity is onSaveInstanceState().

有一個你能在那裏,保存你的活動當前狀態的方法是onSaveInstanceState().方法.

The system calls this method before making the activity vulnerable to being destroyed and passes it a Bundle object.

系統在使得某活動變得容易被銷燬以前,調用這個方法,並傳一個Bundle對象給它.

The Bundle is where you can store state information about the activity as name-value pairs, using methods such as putString().

你能夠在Bundle那兒,把你的活動的相關信息當成一個名字值對(name-value pairs)保存起來,經過使用相似於putString()的方法

Then, if the system kills your activity's process and the user navigates back to your activity, the system passes the Bundle to onCreate() so you can restore the activity state you saved during onSaveInstanceState().

而後,若是系統殺掉了你的活動的進程,而且用戶導航返回到你的活動時,系傳一個BundleonCreate() 方法,以便你能從新恢,你在onSaveInstanceState()中保存的活動的狀態.

If there is no state information to restore, then the Bundle passed to onCreate() is null.若是沒有狀態信息要恢得,那麼傳給onCreate() 方法的Bundle是null值

Note: There's no guarantee that onSaveInstanceState() will be called before your activity is destroyed,

注意,不能保證在你的活動被銷燬前,onSaveInstanceState() 方法將被調用

because there are cases in which it won't be necessary to save the state   由於有些狀況沒必要保存狀態

(such as when the user leaves your activity using the BACK key, because the user is explicitly closing the activity).

當用戶使用返回鍵離開你的活動時,由於用戶明顯要關掉你的活動

If the method is called, it is always called before onStop() and possibly before onPause().

若是這個方法被調用,它將常常在調用onStop() 方法以前被調用,或可能在調用onPause()方法以前調用

However, even if you do nothing and do not implement onSaveInstanceState(), some of the activity state is restored by the Activity class's default implementation of onSaveInstanceState().

而後,即便你沒有作任保事,或沒有實現onSaveInstanceState()方法,一些活動的狀態將被類的onSaveInstanceState()方法的默認實現恢復

Specifically, the default implementation calls onSaveInstanceState() for every View in the layout, which allows each view to provide information about itself that should be saved. 特別是,默認實現爲每個佈局中的View調用onSaveInstanceState() 方法,這樣容許每一個view提供關於它本身須要保存的信息

Almost every widget in the Android framework implements this method as appropriate, 幾乎Android框架的每一個widget,都相應的實現了這個方法.

such that any visible changes to the UI are automatically saved and restored when your activity is recreated.

好比當你的活動被重建立時,對UI任何可見的改變將自動保存和恢復

For example, the EditText widget saves any text entered by the user and the CheckBox widget saves whether it's checked or not.

好比,EditTextwidget保存了你輸入的任何文本,並CheckBoxwidget保存了是否它被複選。

The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state

你必需要作的惟一工做是,爲每個你想保存它的狀態的widget提供一個惟一的ID(使用android:id這個屬性).

If a widget does not have an ID, then it cannot save its state.如個widget沒有ID,那麼它的狀態將不能被保存

You can also explicitly stop a view in your layout from saving its state by setting the android:saveEnabled attribute to "false" or by calling the setSaveEnabled() method.

你也能夠顯式的阻止你的佈局保存它的狀態,經過設置android:saveEnabled 屬性爲」false」,或調用方法設置它爲」false」

Usually, you should not disable this, but you might if you want to restore the state of the activity UI differently。

一般,你不該禁止這個功能,但若是你想恢復UI的不一樣狀態,你能夠這麼作

Although the default implementation of onSaveInstanceState() saves useful information about your activity's UI, you still might need to override it to save additional information.

雖然onSaveInstanceState()方法的默認實現保存了,你的活動的UI的有用的信息,你仍可能須要複寫它,保存另外的信息

For example, you might need to save member values that changed during the activity's life (which might correlate to values restored in the UI, but the members that hold those UI values are not restored, by default).

好比,你可能須要保存在活動生命週期改變的成員值,(這些值,多是與恢得UI相關的值,但通常狀況下,成員保存的這些UI值不須要恢復)

Because the default implementation of onSaveInstanceState() helps save the state of the UI, 由於,onSaveInstanceState() 方法的默認實現幫助保存了UI的狀態.

if you override the method in order to save additional state information, you should always call the superclass implementation of onSaveInstanceState() before doing any work.

若是你要複寫這個方法,來保存另外的狀態信息,你應該總在,作任何其餘事情以前調用超類的onSaveInstanceState() 方法.

Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only to record the transient state of the activity (the state of the UI)—

注意:由於onSaveInstanceState() 方法不能保證被調用,因此你應僅僅用它記錄活動的暫時的狀態(UI的狀態)

you should never use it to store persistent data. Instead, you should use onPause() to store persistent data (such as data that should be saved to a database) when the user leaves the activity.你不該用它存儲持久數據,而是,當用戶離開活動時,你應用onPause() 方法存儲持久數據(好比要保存到數據庫的數據).

A good way to test your application's ability to restore its state is to simply rotate the device so that the screen orientation changes.

一個測試你的應用能恢得它的狀態的好方法是,轉動你的設備的,讓屏幕的方向發生改變

When the screen orientation changes, the system destroys and recreates the activity in order to apply alternative resources that might be available for the new orientation.

當屏幕方向發生改變時,系統爲了應用對新的屏幕方向可選取的資源,它將銷燬並從新建立該活動。

For this reason alone, it's very important that your activity completely restores its state when it is recreated, because users regularly rotate the screen while using applications.

就這一理由,就足以說明,當活動被從新建立時,你的活動能徹底恢復它的狀態很是重要,由於在使用應用時,用戶經常轉動屏幕。

Handling configuration changes處理配置的變化

Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language).

一些設備的配在運行時可能會改變,(好比屏幕方向,鍵盤功能,和語言)

When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed immediately by onCreate()).

當這些改變發生時,Android從新啓動運行中的Activity(在onDestroy() 方法調用後,當即緊跟着調用onCreate()方法).

The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that you've provided.

重啓行爲,經過自動裝載你提供的應用的可選資源,幫助你的應用適應新的配置

If you design your activity to properly handle this event, it will be more resilient to unexpected events in the activity lifecycle.

若是你設置你的活動去相應的處理這些事件,在活動的生命週期中,將會有更多的意料不到的事件會反彈。

The best way to handle a configuration change, such as a change in the screen orientation, is to simply preserve the state of your application using onSaveInstanceState() and onRestoreInstanceState() (or onCreate()), as discussed in the previous section.

處理這種配置改變(好比屏幕方法改變)的最好方法,就是像前面章節討論的,使用onSaveInstanceState() 方法和onRestoreInstanceState()方法(或onCreate()方法)簡單的預保留你的應用的狀態.

For a detailed discussion about configuration changes that happen at runtime and how you should handle them, read Handling Runtime Changes.

更多關於在運行時配置發生改變,而且你應怎麼處理這些改變的詳細討論,請讀Handling Runtime Changes.

Coordinating activities協調活動

When one activity starts another, they both experience lifecycle transitions. 當一個活動啓動另外一個時,它們都經歷生命週期的轉換

The first activity pauses and stops (though, it won't stop if it's still visible in the background), while the other activity is created.

當另外一個活動被建立時,第一個活動暫停並中止(但,若是它仍然在背景可見,它將不會中止)

In case these activities share data saved to disc or elsewhere, it's important to understand that the first activity is not completely stopped before the second one is created.

假使這些活動共享的數據保存到磁盤或其也的地方,理解在第二個活動在被建立以前第一個活動並無徹底中止是很是重要的.

Rather, the process of starting the second one overlaps with the process of stopping the first one.更進一步來講,開啓第二個活動的過程和中止第一個活動的過程是重疊的.

The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process and one is starting the other. Here's the order of operations that occur when Activity A starts Acivity B: 生命週期的回調方法的順序是很好肯定的,特別是在同一個進程中,一個活動開啓另外一個活動時.這裏是當活動A啓動活動B 時操做的順序.

  1. Activity A's onPause() method executes. 活動A的方法執行
  2. Activity B's onCreate(), onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)
  3. 活動B的onCreate(), onStart(), 和onResume() 方法按順執行(這時活動B捅有用戶焦點)
  4. Then, if Activity A is no longer visible on screen, its onStop() method executes. 而後,若是活動A在屏上再也不可見時,它的onStop()方法執行

This predictable sequence of lifecycle callbacks allows you to manage the transition of information from one activity to another.

這個預先指定的順序,容許你管理從一個活動到另外一個活動的信息轉換.

For example, if you must write to a database when the first activity stops so that the following activity can read it, then you should write to the database during onPause() instead of during onStop().好比,若是當第一個活動加中止時,你必須寫入到數據庫,以備後面的活動讀取它,那麼你應在onPause() 方法寫入到數據庫,而不是在onStop().方法中.

相關文章
相關標籤/搜索