Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> API翻譯 --- Activities

API翻譯 --- Activities

編輯:關於Android編程

IN THIS DOCUMENT

Creating an Activity 創建一個Activity

Implementing a user interface 實現用戶界面

Declaring the activity in the manifest 在清單文件中聲明Activity

Starting an Activity 啟動一個Activivty

Starting an activity for a result啟動一個Activity得到結果

Shutting Down an Activity 關閉Activity

Managing the Activity Lifecycle 管理Activity的生命周期

Implementing the lifecycle callbacks實現生命周期的回調

Saving activity state 保存activity的狀態

Handling configuration changes 處理配置的修改

Coordinating activities Activity之間的協作

KEY CLASSES

Activity

SEE ALSO

Tasks and Back Stack

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

Activity是一個應用程序組件,它提供了為做一些事情與用戶交互的屏幕,如撥打電話,拍照,發送電子郵件,或查看地圖。每個Activity都被給予了一個窗口繪制它的用戶界面。通常窗口填充屏幕,但是總是小於屏幕,浮動在其他窗口上。

An application usually consists of multiple activities that are loosely bound to each other. 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. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous acti看vnmvity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses theBackbutton, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in theTasks and Back Stackdocument.)

一個應用程序通常由松散綁定的多個Activity組成。通常,一個應用程序中的Activity被指定為“主”Activity,這是在第一次啟動應用程序的時候提供給用戶。每個Activity都可以啟動另一個Activity以執行不同的動作。每一次新的Activity開始,以前的Activity停止,系統把Activity保存在堆棧中 (“回棧”)。當一個新的活動開始,它被推到返回堆棧中和失去用戶焦點。回堆棧遵守基本的“後進,先出堆棧機制,因此,當用戶完成當前Activity並按下返回按鈕,則彈出堆棧(和破壞)和恢復前一個活動。(後退堆棧進行了更多的任務和後退堆棧文檔。)

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. 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. 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. These state transitions are all part of the activity lifecycle.

當一個Activity停止,由於一個新的Activity開始的時候,它是通過活動的生命周期回調方法,通知這種狀態的改變。一個Activity可以接收有幾個回調方法,系統根據其狀態的變化判斷是否創建它,阻止它,恢復它,或摧毀它.每一次回調提供您機會完成特定的工作以適應狀態的改變。例如,當停止,你的活動應該釋放大型對象,如網絡或數據庫連接。當活動恢復,你可以重新獲得必要的資源和恢復被中斷的動作。這些狀態轉換是Activity的所有的生命周期。

 

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


To create an activity, you must create a subclass ofActivity(or an existing subclass of it). 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:

創建一個Activity,你必須創建一個Activity的子類(或現有的子類)。子類中,當其生命周期的不同狀態之間的轉換Activity的時候,你需要實現系統調用的回調方法。例如創建Activity時,停止,恢復或銷毀。最重要的兩個回調方法:

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 callsetContentView()to define the layout for the activity's user interface.

您必須實現這個方法。當創建Activity的時候系統調用這個方法。在你實現中,你應該初始化Activity的基本要素。最重要的是,你必須調用setContentView()來定義Activity的用戶界面的布局。

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

系統調用此方法作為第一個跡象表明用戶離開你Activity(盡管它並不總是意味著Activity銷毀了)。這通常是你應該提交的任何更改,應保存在當前用戶會話(因為用戶可能不回來)。

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 aboutManaging the Activity Lifecycle.

還有其他幾個生命周期回調方法,您應該使用Activity之間為了提供流暢的用戶體驗和處理意外中導致你的Activity停止,甚至毀滅。稍後將討論所有的生命周期回調方法,在下一節關於管理Activity生命周期。

Implementing a user interface

The user interface for an activity is provided by a hierarchy of views—objects derived from theViewclass. Each view controls a particular rectangular space within the activity's window and can respond to user interaction. For example, a view might be a button that initiates an action when the user touches it.

一個Activity的用戶界面是由視圖-對象衍生的視圖類的層次結構。每個視圖控制特定的矩形空間內Activity的窗口,可以響應用戶交互。例如,一個視圖可能是一個按鈕,當用戶觸摸它啟動一個動作。

Android provides a number of ready-made views that you can use to design and organize your layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image. "Layouts" are views derived fromViewGroupthat provide a unique layout model for its child views, such as a linear layout, a grid layout, or relative layout. You can also subclass theViewandViewGroupclasses (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.

Android提供了許多現成的視圖,您可以使用它們來設計和組織你的布局。“窗口小部件”視圖,提供一個屏幕視覺和互動元素,比如一個按鈕,文本字段、復選框,或只是一個形象。“布局”視圖來自ViewGroup提供一個獨特的子視圖的布局模型,如線性布局,網格布局,或相對布局。您還可以使用子類視圖和ViewGroup類(或現有的子類)來創建自己的小部件和布局,將它們應用到Activity。

 

The most common way to define a layout using views is with an XML layout file saved in your application resources. This way, you can maintain the design of your user interface separately from the source code that defines the activity's behavior. You can set the layout as the UI for your activity withsetContentView(), passing the resource ID for the layout. However, you can also create newViews in your activity code and build a view hierarchy by inserting newViews into aViewGroup, then use that layout by passing the rootViewGrouptosetContentView().

定義一個布局的一般方式是使用保存在應用資源中的xml文件。使用這種方式,你可以保持用戶界面的設計和activity動作的源碼分開。你可以使用setContentView(),通過布局的資源ID,設置activity的布局。你也可以在activity中創建一個視圖類,通過在視圖組中插入新視圖來實現,來構建一個視圖樹。根視圖組通過setContentView()設置。

 

For information about creating a user interface, see theUser Interfacedocumentation.

創建用戶界面的更多信息,看下用戶界面的文檔。

Declaring the activity in the manifest

You must declare your activity in the manifest file in order for it to be accessible to the system. To declare your activity, open your manifest file and add anelement as a child of theelement. For example:

你必須在清單文件中聲明Activity,以便它可以訪問系統。打開你的清單文件,聲明你的activity,在 元素中添加一個的子元素。例如:

          ...
   ...

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. Theandroid:nameattribute is the only required attribute—it specifies the class name of the activity. 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).

還有其他幾種屬性,您可以包括在這個元素中,為activity定義屬性標簽,活動的圖標,或一個主題風格的UI。android: name是唯一指定的類名。一旦發布您的應用程序,您不應該改變這個名字,因為如果你這樣做,你可能會打破一些功能,如應用程序快捷鍵(閱讀博客,不能改變的事情)。

See theelement reference for more information about declaring your activity in the manifest.

在清單文件中聲明activity更多信息,你可以查看應用清單的元素相關。

Using intent filters

Anelement can also specify various intent filters—using theelement—in order to declare how other application components may activate it.

一個元素還可以指定各種意圖filters-using < intent-filter >元素,來聲明其他應用程序組件如何激活它。

When you create a new application using the Android SDK tools, 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:

當你使用Android SDK工具創建一個新的應用程序,自動為你創建一個Activity,包括一個意圖過濾器,聲明Activity響應的“主要”行動和類別。意圖過濾器如下所示:


Theelement specifies that this is the "main" entry point to the application. Theelement specifies that this activity should be listed in the system's application launcher (to allow users to launch this 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. Only one activity should have the "main" action and "launcher" category, as in the previous example. 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).

如果你想讓你的應用程序是獨立的,不允許其他應用程序來激活它的Activity,那麼你不需要任何其他意圖過濾器。只有一個Activty應該有動作和分類。如前面的例子。如果你不想讓Acitivity響應其他應用程序,你可以啟動他們,你可以自己使用顯式意圖(在下一節中討論)。

 

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 anthat includes anelement and, optionally, aelement and/or aelement. These elements specify the type of intent to which your activity can respond.

然而,如果你希望你的Activity來應對隱含的意圖,與其他應用程序區分開,那麼你必須定義額外的意圖過濾器為您的activity。為你想回應每種類型的意圖,您必須包含一個< intent-filter >,包含一個元素,元素或一個元素。這些元素指定類型的activity可以回應你的意圖。

For more information about how your activities can respond to intents, see theIntents and Intent Filtersdocument.

activity響應意圖的更多信息,你可以查看Intents and Intent Filters文檔

Starting an Activity


You can start another activity by callingstartActivity(), passing it anIntentthat describes the activity you want to start. 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). An intent can also carry small amounts of data to be used by the activity that is started.

你可以通過調用startactivity()啟動另一個acitity,它傳遞一個意圖,描述你想啟動的activity。目的指定確切的activity你想開始或描述你想執行的操作類型(系統會選擇合適的Activity給你,它甚至可以在不同的應用中)。一個意圖也可以包含少量的數據在被啟動的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 namedSignInActivity:

當你自己的應用程序在運行時,你需要經常地推出一個已知的activity。你可以通過創建一個意圖,明確定義了你想啟動的activity,使用類名稱。例如,這裡有一個activity啟動另一個Activity:

Intent intent =newIntent(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:

然而,你的應用程序可能還需要執行一些動作,如發送電子郵件,文本消息,或狀態更新,使用來自你的activity的數據。在這種情況下,你的應用程序可能沒有執行該動作的activity,所以你可以利用設備上的其它應用程序提供的activity,它能為你執行動作。意圖的真正價值是你可以創建一個意圖,描述你想執行的動作,系統從另一個應用程序啟動適當的activity。如果有多個可以處理意圖的Activity,然後用戶可以選擇使用一個。例如,如果你想讓用戶發送電子郵件,您可以創建以下目的:

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

TheEXTRA_EMAILextra added to the intent is a string array of email addresses to which the email should be sent. 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. In this situation, the email application's activity starts and when the user is done, your activity resumes.

該 EXTRA_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 callingstartActivityForResult()(instead ofstartActivity()). To then receive the result from the subsequent activity, implement theonActivityResult()callback method. When the subsequent activity is done, it returns a result in anIntentto youronActivityResult()method.

有時,你可能想從你開始activity得到的結果。在這種情況下,通過調用startactivityForResult()啟動Acitivity(而不是startactivity())。然後接收來自後續Activity的結果,實現onActivityResult()回調方法。當隨後Activity完成,它返回在意向你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:

例如,你可能想讓用戶選擇一個聯系人,那麼你的Activity可以通過在聯系人中得到的信息做某事。這裡是你如何創造這樣的意圖和處理結果:

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(),     newString[]{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 youronActivityResult()method in order to handle an activity result. The first condition checks whether the request was successful—if it was, then theresultCodewill beRESULT_OK—and whether the request to which this result is responding is known—in this case, therequestCodematches the second parameter sent withstartActivityForResult(). From there, the code handles the activity result by querying the data returned in anIntent(thedataparameter).

這個例子表明,你應該用你的onActivityResult()方法以處理Acitivity的結果的基本邏輯。第一個條件檢查請求是否成功,如果是,那麼ResultCode是RESULT_OK,並且是否請求的響應結果是已知在這種情況下,requestCode匹配發送startActivityForResult()第二個參數。從那裡,代碼處理Activity的結果通過查詢數據的意圖返回(數據參數)。

What happens is, aContentResolverperforms a query against a content provider, which returns aCursorthat allows the queried data to be read. For more information, see theContent Providersdocument.

所發生的是,一個ContentResolver執行對內容提供商的查詢,並返回一個指針,允許讀取被查詢的數據。有關更多信息,請參見內容提供者文檔。

For more information about using intents, see theIntents and Intent Filtersdocument.

關於使用意圖的更多信息,請參見意圖和意圖過濾器文件。

Shutting Down an Activity


You can shut down an activity by calling itsfinish()method. You can also shut down a separate activity that you previously started by callingfinishActivity().

你可以關閉一個activity,通過調用它的finish()方法。你也可以關閉一個單獨的activity,在以前通過調用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.

注意:在大多數情況下,你不應該明確使用這些方法關閉Activity。在下一節討論關於活動的生命周期,Android系統為你管理一個activity的生命,所以你不需要關閉自己的Activity。調用這些方法可能產生不利影響的預期的用戶體驗,應該只用於當你絕對不希望用戶返回到該Activity的時候。

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.

通過實現回調方法管理你的activity的生命周期,對你的應用時至關重要,使用應用變得更加強大和靈活。一個activity的生命周期直接影響到與其關聯的其他activity,其任務和後退堆棧。

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".)

  • acitivity是在屏幕的前台和擁有用戶焦點。

  • 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 (theActivityobject 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.

  • 另一個的activity在前台並具有焦點,但原來的activity仍然是可見的。也就是說,另一個Activity在這個activity的頂部可見或部分透明或沒有覆蓋整個屏幕。這個暫停的activit依然存活(Activity對象保留在內存中,它保持所有狀態和成員信息,並保持附著到窗口管理器),但在極低的內存的情況下,可以被系統殺死。

  • Stopped

  • The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (theActivityobject is retained in memory, it maintains all state and member information, but isnotattached 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.

  • activity是由另一個activity完全遮蔽(activity現在在“背景”)。停止activity也仍然活著(activity對象保留在內存中,它保持所有狀態和成員信息,但沒有連接到窗口管理器)。然而,它是用戶不可見的,在其它地方需要內存時它可以被系統殺死。

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling itsfinish()method), or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over.

如果activity被暫停或停止時,系統能夠將它從內存中關閉掉(調用它的finish()法),或簡單地殺死它的進程。當activity再次被打開(完成的或殺死之後),它必須所有的重新建立。

Implementing the lifecycle callbacks管理Activity生命周期

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:

當一個activity過渡到了上述不同的狀態,它是通過調用不同的回調方法。所有的回調方法你可以重載做適當的工作。下面包括每個基本周期的方法:

publicclassExampleActivityextendsActivity{   @Override   publicvoidonCreate(Bundle savedInstanceState){     super.onCreate(savedInstanceState);     // The activity is being created.   }   @Override   protectedvoidonStart(){     super.onStart();     // The activity is about to become visible.   }   @Override   protectedvoidonResume(){     super.onResume();     // The activity has become visible (it is now "resumed").   }   @Override   protectedvoidonPause(){     super.onPause();     // Another activity is taking focus (this activity is about to be "paused").   }   @Override   protectedvoidonStop(){     super.onStop();     // The activity is no longer visible (it is now "stopped")   }   @Override   protectedvoidonDestroy(){     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:

綜合起來,這些方法定義一個activity的整個生命周期。通過實施這些方法,你可以監視activity周期的三個嵌套循環:

  • Theentire lifetimeof an activity happens between the call toonCreate()and the call toonDestroy(). Your activity should perform setup of "global" state (such as defining layout) inonCreate(), and release all remaining resources inonDestroy(). For example, if your activity has a thread running in the background to download data from the network, it might create that thread inonCreate()and then stop the thread inonDestroy().

  • 一個activity的整個生命周期中發生的oncreate()和ondestroy()之間。你的activity應該在oncreate()中執行“全局”的狀態設置(如定義布局),和ondestroy()中釋放所有剩余的資源。例如,如果你的activity有一個線程運行在後台從網絡下載的數據,它會在oncreate()中創建線程然後在ondestroy()中停止線程。

  • Thevisible lifetimeof an activity happens between the call toonStart()and the call toonStop(). 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. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register aBroadcastReceiverinonStart()to monitor changes that impact your UI, and unregister it inonStop()when the user can no longer see what you are displaying. The system might callonStart()andonStop()multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.

  • 一個activity的可見周期發生onstart()和onstop()之間。在這段時間,用戶可以在屏幕上看到activity並與它進行交互。例如,當一個新的活動調用onstop(),它是一個不可見的。這兩個方法之間,你可以保持activity需要顯示給用戶的資源。例如,您可以注冊一個BroadcastReceiver的 onstart()監視影響你的用戶界面的變化,當用戶無法看到你的顯示的時候,你可以在在onstop()中取消它。在Activity的整個生命周期中,activity可見和不可見的變化過程中,系統可能多次調用onStart()和onStop()。

  • Theforeground lifetimeof an activity happens between the call toonResume()and the call toonPause(). During this time, the activity is in front of all other activities on screen and has user input focus. 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. 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.

  • 一個activity的前台周期發生onresume()和onpause()之間。在這段時間,activity在屏幕上的所有其他activity之前,並具有用戶輸入焦點。一個activity可以頻繁進出前台。例如當設備進入睡眠或當一個對話框出現的時候onPause()方法被調用。因為這個狀態經常轉換,這兩種方法的代碼必須是輕量級的避免導致用戶等待的緩慢過渡。

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的狀態之間轉換的路徑。矩形代表你可以實現不同狀態轉換時,回調方法的執行順序。

Figure 1.The activity lifecycle.

The same lifecycle callback methods are listed in table 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.

相同的生命周期回調方法表1中列出,詳細描述每一個回調方法和定位中的每一個活動的整體生命周期,包括系統是否可以殺死活動完成後的回調方法。

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 (seeSaving Activity State, later).

Always followed byonStart().

當activity首次創建。這裡你應該處理靜態設置。比如創建視圖,將數據綁定到列表等。如果狀態可以被捕獲,這種方法是通過Bundle可以得到activity的先前狀態。(見Activity保存狀態)。總是跟著onstart()。

No onStart()   onRestart() Called after the activity has been stopped, just prior to it being started again.

Always followed byonStart()

activity啟動之前,停止之後。總是跟著onstart()

No onStart() onStart() Called just before the activity becomes visible to the user.

Followed byonResume()if the activity comes to the foreground, oronStop()if it becomes hidden.

就在activity變得可見的時候調用。如果之後前台可見,調用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 byonPause().

在activity將要與用戶的交互的時候調用。此時activity是在activity堆棧的頂部,而且正在得到用戶的輸入。總是跟著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 byonResume()if the activity returns back to the front, or byonStop()if it becomes invisible to the user.

當系統開始恢復另一個activity。這種方法通常用於提交未保存的更改的持久化數據,停止動畫和可能消耗CPU的其他動作等。它應該非常快,因為只有它返回,其他的activity才能恢復。另外的activtiy返回到前台,將調用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 byonRestart()if the activity is coming back to interact with the user, or byonDestroy()if this activity is going away.

當activity不再可見。這可能是因為它被破壞,或者因為另一個activity(無論是現有的或新的)已經恢復並覆蓋。若activity與用戶交互調用onRestart(),如果activity銷毀通過調用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 calledfinish()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 theisFinishing()method

onDestroy() 銷毀actvity之前調用。activity最後能接收到的調用方法。可能是activity已經完成(有人調用finish()),或者因為系統暫時破壞該activity實例的節省空間。你能區分這兩種情況的isfinishing()方法。.

Yes nothing

The column labeled "Killable after?" indicates whether or not the system can kill the process hosting the activity at any timeafter the method returns, without executing another line of the activity's code. Three methods are marked "yes": (onPause(),onStop(), andonDestroy()). BecauseonPause()is the first of the three, once the activity is created,onPause()is the last method that's guaranteed to be called before the processcanbe killed—if the system must recover memory in an emergency, thenonStop()andonDestroy()might not be called. Therefore, you should useonPause()to write crucial persistent data (such as user edits) to storage. However, you should be selective about what information must be retained duringonPause(), because any blocking procedures in this method block the transition to the next activity and slow the user experience.

列標記為“之後被殺死“顯示系統是否在主activity方法返回後可以主進程隨時殺死,不會執行activity的其他代碼。三種方法被標記為“是”:(onPause(),onStop(),和onDestroy())。因為onPause()是三個方法中第一個被調用,一旦activity創建後,onPause()能保證系統在殺死進程之前保證能調用到的方法,然後onStop()和onDestroy()可能不會被調用。因此,你應該使用onPause()寫重要的持久數據存儲(如用戶編輯)。然而,你應該選擇哪些信息必須保留在onPause(),在此方法中,任何阻塞過程,將會阻塞過渡到下一個activity並降低的用戶體驗。

Methods that are marked "No" in theKillablecolumn protect the process hosting the activity from being killed from the moment they are called. Thus, an activity is killable from the timeonPause()returns to the timeonResume()is called. It will not again be killable untilonPause()is again called and returns.

方法標記Killable列保護過程中的“不”的activity,此時他們不會被被殺。因此,一個activity從onPause()返回到onResume()的過程中是可能被殺死的。在下次onPause()被調用,並返回之前不會被殺死。

Note:An activity that's not technically "killable" by this definition in table 1 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 theProcesses and Threadingdocument.

注意:一個activity,並不是技術上“可被殺”,系統就會殺死,只有在極端情況下會發生時,沒有其他辦法。當某個activity可能會殺死.更多的討論進程和線程文檔。

Saving activity state保存Activity狀態

The introduction toManaging the Activity Lifecyclebriefly mentions that when an activity is paused or stopped, the state of the activity is retained. This is true because theActivityobject is still held in memory when it is paused or stopped—all information about its members and current state is still alive. Thus, any changes the user made within the activity are retained so that when the activity returns to the foreground (when it "resumes"), those changes are still there.

對管理activity生命周期的簡要介紹中提到,當activity暫停或停止時,activity的狀態被保留。這是因為activity暫停或停止的時候,activity對象仍然保留在內存中,其成員和當前狀態的所有信息都是還活著。因此,在用戶模式下的任何對activity的操作,在activity返回到前台的時候將被恢復。

However, when the system destroys an activity in order to recover memory, theActivityobject is destroyed, so the system cannot simply resume it with its state intact. Instead, the system must recreate theActivityobject if the user navigates back to it. 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:onSaveInstanceState().

然而,系統為了回收資源而銷毀activity。這是系統不能簡單的恢復到原來的完整狀態。相反,系統必須重新創建activity對象,如果用戶導航回到它。然而,用戶更期望activity是否能恢復到原來的狀態。在這種情況下,你可以確保關於活動狀態的重要信息是通過執行一個附加的方法onSaveInstanceState(),允許你保存你的Activity的狀態信息保存。

The system callsonSaveInstanceState()before making the activity vulnerable to destruction. The system passes this method aBundlein which you can save state information about the activity as name-value pairs, using methods such asputString()andputInt(). Then, if the system kills your application process and the user navigates back to your activity, the system recreates the activity and passes theBundleto bothonCreate()andonRestoreInstanceState(). Using either of these methods, you can extract your saved state from theBundleand restore the activity state. If there is no state information to restore, then theBundlepassed to you is null (which is the case when the activity is created for the first time).

在activity不穩定之前,系統調用onSaveInstanceState()保存數據。該系統通過傳遞一個Bundle,你能通過鍵值對的方式保存activity信息使用方法,如putstring()和putint()。然後,如果系統殺死你的應用程序,當你返回到你的activity的時候,系統會重新創建activity,通過對onCreate()和onRestoreinstancestate()提取你保存的狀態和恢復活動狀態。如果沒有狀態信息恢復,Bundle為空(這種情況時,活動是在第一次創建)。

\

Figure 2.The two ways in which an activity returns to user focus with its state intact: either the activity is destroyed, then recreated and the activity must restore the previously saved state, or the activity is stopped, then resumed and the activity state remains intact.

這兩種方法讓activity返回用戶焦點:要麼銷毀activity,然後創建activity,必須恢復以前保存的狀態,或者停止活動,然後恢復activity狀態保持不變。

Note:There's no guarantee thatonSaveInstanceState()will be called before your activity is destroyed, because there are cases in which it won't be necessary to save the state (such as when the user leaves your activity using theBackbutton, because the user is explicitly closing the activity). If the system callsonSaveInstanceState(), it does so beforeonStop()and possibly beforeonPause().

在activtity被銷毀之前,actvity不能保證onSaveInstanceState()調用。因為在這種情況下,它不會是必要的保存狀態(例如,當用戶離開你的activity使用後退按鈕,因為用戶明確關閉activity)。如果系統調用onSaveInstanceState(),它能在onStop()可能之前或onPause()之前調用。

However, even if you do nothing and do not implementonSaveInstanceState(), some of the activity state is restored by theActivityclass's default implementation ofonSaveInstanceState(). Specifically, the default implementation calls the correspondingonSaveInstanceState()method for everyViewin the layout, which allows each view to provide information about itself that should be saved. Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved and restored when your activity is recreated. For example, theEditTextwidget saves any text entered by the user and theCheckBoxwidget saves whether it's checked or not. The only work required by you is to provide a unique ID (with theandroid:idattribute) for each widget you want to save its state. If a widget does not have an ID, then the system cannot save its state.

然而,即使你什麼都不做,不執行onSaveInstanceState(),某些Activity狀態是由Activity類的默認onSaveInstanceState()實現恢復。具體來說,默認實現調用布局中的每個視圖對應的onSaveInstanceState()方法,允許每個視圖提供關於自身的信息應保存。在Android框架幾乎每一個部件實現這個適當的方法,使得對用戶界面的任何可見的變化進行自動保存和恢復你的activity被重新創建。例如,EditText小部件保存任何文本由用戶和復選框控件保存它是否被選擇。你唯一需要的工作是提供一個獨特的ID(與Android:id屬性)為每個控件你想保存其狀態。如果插件沒有ID,然後系統將不能保存它的狀態。

You can also explicitly stop a view in your layout from saving its state by setting theandroid:saveEnabledattribute to"false"or by calling thesetSaveEnabled()method. Usually, you should not disable this, but you might if you want to restore the state of the activity UI differently.

你也可以顯式的阻止視圖保存其狀態,通過設置android:saveEnabled為false,或調用setSaveEnable()。一般情況下,你不該禁用它。但你想使你的activity在恢復狀態時,有不同的UI效果,你就需要啟動它。

 

Although the default implementation ofonSaveInstanceState()saves useful information about your activity's UI, you still might need to override it to save additional information. 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).

盡管默認的保存activity界面的有用信息的onSaveInstanceState(),你仍然可能需要重寫它。例如,您可能需要在恢復activity中關聯成員值的改變(默認情況下,UI值的成員都不會改變)。

 

Because the default implementation ofonSaveInstanceState()helps save the state of the UI, if you override the method in order to save additional state information, you should always call the superclass implementation ofonSaveInstanceState()before doing any work. Likewise, you should also call the superclass implementation ofonRestoreInstanceState()if you override it, so the default implementation can restore view states.

因為onsaveinstancestate()默認的實現有助於節省用戶界面的狀態,如果重寫的方法,節省額外的狀態信息,你應該總是做任何工作之前調用父類的實現onsaveinstancestate()。同樣的,你也應該如果重寫它調用的實現onrestoreinstancestate() ,所以默認實現可以還原視圖狀態。

 

Note:BecauseonSaveInstanceState()is not guaranteed to be called, you should use it only to record the transient state of the activity (the state of the UI)—you should never use it to store persistent data. Instead, you should useonPause()to store persistent data (such as data that should be saved to a database) when the user leaves the activity.

 

因為onsaveinstancestate()不能保證調用,你應該只使用它來記錄activity的瞬態(UI的狀態)-你不應該使用它來存儲數據持久性。相反,你應該使用onpause()存儲持久性數據(如數據應保存到數據庫)當用戶離開activity。

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 screen configuration. 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.

測試你的應用程序恢復狀態的能力的是簡單的旋轉裝置使屏幕方向變化的好方法。當屏幕的方向改變時,系統銷毀並重新創建activity以應用替代資源,可用於新的屏幕配置。僅僅出於這個原因,它是非常重要的,你的活動完全恢復狀態時,它是重現,因為用戶在使用應用程序定期旋轉屏幕。

Handling configuration changes處理配置更改

Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android recreates the running activity (the system callsonDestroy(), then immediately callsonCreate()). This behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that you've provided (such as different layouts for different screen orientations and sizes).

一些設備配置在運行時可以改變(比如屏幕方向,鍵盤的可用性,和語言)。當發生這樣的變化,Android重新運行的activity(系統調用ondestroy(),然後立即打電話oncreate())。此行為是設計來幫助您的應用程序的自動裝載的替代資源,你提供的應用的適應新的配置(如不同的屏幕方向和大小不同的布局)。

If you properly design your activity to handle a restart due to a screen orientation change and restore the activity state as described above, your application will be more resilient to other unexpected events in the activity lifecycle.

如果你正確地設計你的activity,由於屏幕方向改變重新啟動,如上面所描述的恢復活動狀態,你的應用在acitivity生命周期中對於其他突發性事件,更具彈性的。

The best way to handle such a restart is to save and restore the state of your activity usingonSaveInstanceState()andonRestoreInstanceState()(oronCreate()), as discussed in the previous section.

最好的辦法來處理這樣的重新啟動是保存和恢復你的活動和使用onsaveinstancestate() onrestoreinstancestate()(或oncreate()),如在上一節討論。

For more information about configuration changes that happen at runtime and how you can handle them, read the guide toHandling 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.

當一個Activity啟動另一個,他們都經歷生命周期轉換。當其他的activity創建,第一個activity暫停和停止(雖然,如果它仍然在後台停止)。如果這些activity共享的數據保存到磁盤或其他地方,重要的是知道,第二個activity重建之前,第一個acitiviy會不會完全停止的,而不是第二個activity的進程覆蓋了第一個activity的進程。

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:

生命周期回調的順序是明確的,特別是當兩個Activity是同一個進程中,一個activity啟動另外一個activity的時候。活動開始活動B的操作順序:

  1. Activity A'sonPause()method executes.

    Activity A的onpause()方法執行。

  2. Activity B'sonCreate(),onStart(), andonResume()methods execute in sequence. (Activity B now has user focus.)

activityB的oncreate(),onstart(),和onresume()方法執行的順序。(activityB有用戶焦點。)

Then, if Activity A is no longer visible on screen, itsonStop()method executes.

然後,如果activity不再是顯示在屏幕上,它的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 duringonPause()instead of duringonStop().

 

這個預先指定的順序,允許你管理從一個activity到另一個的轉換信息。例如,如果你要寫一個activity中寫數據庫,讓之後的activity讀取數據庫,你應該在onPause()寫入數據庫,而不是onStop()。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved