【翻譯】Activity

轉載請註明出處:http://blog.csdn.net/kester_/article/details/52503653

參考地址:https://developer.android.com/reference/android/app/Activity.html

Activity

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup). There are two methods almost all subclasses of Activity will implement:
Activity是用戶可以簡單粗暴進行使用的東西。幾乎所有的Activity都與用戶關聯,所以你可以通過setContentView(View)來把你的UI元素放置到Activity來讓Activity創建一個窗口。Activity經常是以全屏形式展現給世人,但是其實它還可以被用在其他方面,例如懸浮窗(通過windowIsFloating主題設置)或者嵌入到另一個Activity(通過ActivityGroup)。有兩個幾乎所有Activity的子類都會實現的方法:

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.
onCreate(Bundle)是初始化Activity的地方。最重要的是,你會經常在這裏調用setContentView(int)來設置佈局,調用findViewById(int)類來找到對應的小部件進行動態部署。

onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).
onPause()是離開Activity時和用戶交互的地方。最重要的是,用戶的任何改變應該在這個時間點之前完成(通常是ContentProvider在搞數據)。

To be of use with Context.startActivity(), all activity classes must have a corresponding declaration in their package’s AndroidManifest.xml.
通過使用Context.startActivity(),所有的Activity類必須在AndroidManifest.xml有一個對應聲明的包名。

Topics covered here:
主題包括下面幾個:

Fragments
Activity Lifecycle
Configuration Changes
Starting Activities and Getting Results
Saving Persistent State
Permissions
Process Lifecycle


Developer Guides

The Activity class is an important part of an application’s overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform’s application model. For a detailed perspective on the structure of an Android application and how activities behave, please read the Application Fundamentals and Tasks and Back Stack developer guides.
Activity類是應用整個聲明週期很重要的一部分,Activity的啓動和放在一起的方式是平臺應用模型的基礎部分。對於Android application的結構和Activity的行爲的詳細觀點,可以參考開發者指引裏的Applicaiton Fundamentals和Tasks以及Back Stack。

You can also find a detailed discussion about how to create activities in the Activities developer guide.
你也可以在Activities開發者指引裏找到關於如何創建Activity的詳細套路。


Fragments

Starting with HONEYCOMB, Activity implementations can make use of the Fragment class to better modularize their code, build more sophisticated user interfaces for larger screens, and help scale their application between small and large screens.
Android3.0開始出現,Activity使用Fragment類可以更好的模塊化代碼,對大屏幕可以建立更發雜的用戶接口,以及可以幫助適配應用的小屏和大屏。


Activity Lifecycle

Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity – the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.
Acitvity在系統裏使用Activity棧來管理的。當一個新的Activity開啓的時候,它會放到棧頂,變成運行中的Activity - 以前的Activity同時會保留在棧的下面,並且不會回到前臺除非這個新的Activity退出。

An activity has essentially four states:
本質上,一個Activity有四個狀態:

If an activity is in the foreground of the screen (at the top of the stack), it is active or running.
If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
如果一個Activity丟失焦點但仍然可見(一個非全屏或者透明Activity獲得焦點在舊Activity的上面蓋着),狀態爲:paused。一個paused的Activity也是完全活着的(它維持着所有的狀態以及成員信息並且保持依附在window manager上),但內存不足時可以被系統幹掉。

If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
如果一個Activity完全被另一個Activity蓋住,狀態爲:stopped。它仍然維持所有的狀態和成員信息,但是,它對於用戶來說不再可見,所以它的窗口是隱藏的而且系統任何時候需要內存時它都可能會被幹掉。

If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.
如果一個Activity狀態爲paused或者stopped,系統可以通過調用它結束或者直接幹掉它的進程來將它從內存中清理掉。當它再一次展現在世人面前時,它必須完全重啓和恢復到之前的狀態。

The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.
下面的圖展示了Activity的重要狀態。當Activity在不同狀態之間移動時會有一些回調方法,你可以去實現這些回調來操作Activity,這些回調方法用長方形表示。上色了的橢圓表示Activity的主要狀態。

這裏寫圖片描述

There are three key loops you may be interested in monitoring within your activity:
監控你的Activity時有三個關鍵的循環你可能會很感興趣:

The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of “global” state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().
Activity的生命週期起始於第一次調用onCreate(Bundle),知道最後單一的調用onDestroy()。Activity會在onCreate做所有關於“全局的”狀態步驟,並且在onDestroy釋放所有剩餘的資源。例如,如果需要一個後臺運行的線程從網絡上下載數據,可以在onCreate()創建線程,在onDestroy()結束線程。

The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. 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 for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
Activity的生命週期中,在onStart()到onStop()之間是可見的生命週期。在此之間,用戶可以在屏幕上看見Activity,儘管它可能不在前臺並且和用戶產生交互。在這兩個方法之間,你可以維持用戶需要展示Activity的資源。例如,你可以在onStart()註冊廣播來監控影響你的UI的變化,並且在onStop()裏反註冊廣播,因爲在此時用戶已經看不到你展示的東西了。onStart()和onStop()方法可以隨着Activity可見和隱藏被多次調用。

The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states – for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered – so the code in these methods should be fairly lightweight.
Activity的生命週期中,onResume()和onPause()之間時是前臺生命週期。在這個時間段內,Activity是在所有其他Activity的前面,並且能和用戶交互。Activity能頻繁地在resumed和paused狀態間切換 – 例如,當設備休眠,當Activity的結果被傳遞,當一個新的intent被傳遞時 – 所以這些方法的代碼應該相當地輕量級。

The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that you can override to do appropriate work when the activity changes state. All activities will implement onCreate(Bundle) to do their initial setup; many will also implement onPause() to commit changes to data and otherwise prepare to stop interacting with the user. You should always call up to your superclass when implementing these methods.
Activity完整的生命週期被下面Activity的方法定義。所有這些方法都是你可以覆寫來做合適的任務的鉤子當Activity改變狀態時。所有的Activity都會實現onCreate(Bundle)來做它們的初始化安裝;許多Activity也會實現onPause()來提交改變數據和做其他準備停止和用戶交互的動作。你在實現這些方法時總是應該調用你的超類。

 public class Activity extends ApplicationContext {
     protected void onCreate(Bundle savedInstanceState);

     protected void onStart();

     protected void onRestart();

     protected void onResume();

     protected void onPause();

     protected void onStop();

     protected void onDestroy();
 }

In general the movement through an activity’s lifecycle looks like this:
一般來說Activity生命週期的移動看起來像這樣:

Method Description Killable? 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, etc. This method also provides you with a Bundle containing the activity’s previously frozen state, if there was one. Always followed by onStart(). No onStart()
onRestart() Called after your activity has been stopped, prior to it being started again.Always followed by onStart() No onStart()
onStart() Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden. No onResume() or onStop()
onResume() Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause(). No onPause()
onPause() Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user. Pre-HONEYCOMB onResume() or onStop()
onStop() Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away. Yes onRestart() or onDestroy()
onDestroy() The final call you receive before your activity is destroyed. This can happen 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. Yes nothing

Note the “Killable” column in the above table – for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed. Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
關於上表中的“Killable”列 - 對於那些被標記爲可殺死的方法,在那個方法返回之後,持有這個Activity的進程可能會被系統在任何時候殺死而不執行下面的代碼。因此,你應該使用onPause()方法來寫任何持久化數據來保存。另外,onSaveInstanceState(Bundle)方法會在Activity被放置到後臺之前被調用,讓你可以保存任何動態實例狀態在Bundle,如果Activity重啓的話點會在onCreate(Bundle)接收。查看Process Lifecycle章節可以看到更多關於聯繫到Activity的生命週期的信息。需要注意的是持久化應該在onPause()做而不是onSaveInstanceState(Bundle)因爲後者不是生命週期的回調,並不是每次都會被調用。

Be aware that these semantics will change slightly 
between applications targeting platforms starting with 
HONEYCOMB vs. those targeting prior platforms. Starting 
with Honeycomb, an application is not in the killable 
state until its onStop() has returned. This impacts when 
onSaveInstanceState(Bundle) may be called (it may be 
safely called after onPause() and allows and application 
to safely wait until onStop() to save persistent state.

需要注意的是這些語法在應用的3.0平臺之後和之前可能會稍微改變。
Android 3.0之後,onStop()返回之前應用是不可殺的。
onSaveInstanceState(Bundle)的調用可能會受影響(它會在onPause()
之後安全地調用並且允許應用在onStop()之前安全地等待,來保存持久化狀
態)。

For those methods that are not marked as being killable, the activity’s process will not be killed by the system starting from the time the method is called and continuing after it returns. Thus an activity is in the killable state, for example, between after onPause() to the start of onResume().
對於那些沒有被標記爲killable的方法,方法在被調用直到返回之前,Activity的進程不會被系統幹掉。因此Activity是處於killable狀態,例如,onPause()之後onResume()之前。(不理解,延伸解讀爲:一個Activity開啓另一個Activity時,前者會調用onPause但是在後者onResume之前,前者不會被系統幹掉,因爲處於不可殺時期;或者解讀爲:一個Activity被放置到後臺只是調用了onPause下次切換回來時會調用onResume,在此期間,也是處於不可殺時期,不會被系統幹掉。)


Configuration Changes

If the configuration of the device (as defined by the Resources.Configuration class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.
如果設備的配置改變(正如Resources.Configuration類定義),所有對用戶展示的接口將需要更新到適配該配置。因爲Activity是和用戶交互的主要途徑,它包括特別是支持來處理配置改變。

Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of onPause(), onStop(), and onDestroy() as appropriate. If the activity had been in the foreground or visible to the user, once onDestroy() is called in that instance then a new instance of the activity will be created, with whatever savedInstanceState the previous instance had generated from onSaveInstanceState(Bundle).
除非你特別指定,否則,配置的改變(例如橫豎屏,語言,輸入法等等)將會導致當前Activity銷燬,通過普通的Activity生命週期過程,onPause(),onStop(),和onDestroy()。如果Activity在前臺或者對用戶可見,一旦這個實例的onDestroy()被調用,新的實例的Activity會被創建,帶着前一個實例在onSaveInstanceState(Bundle)裏保存的東西。

This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.
這代表着結束因爲任何應用資源,包括佈局文件,都會隨着配置值改變。因此僅有的處理配置改變的安全方式是重新檢索所有資源,包括佈局文件,圖片資源,字符串。因爲Activity必須知道如何保存它們的狀態和自己通過狀態重建自己,這是讓Activity通過新配置自己重啓的方便方式。

In some special cases, you may want to bypass restarting of your activity based on one or more types of configuration changes. This is done with the android:configChanges attribute in its manifest. For any types of configuration changes you say that you handle there, you will receive a call to your current activity’s onConfigurationChanged(Configuration) method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(Configuration) will not be called.
在一些特別的情況下,你可能需要忽略基於一個或多個類型配置改變帶來的重啓。通過manifest文件裏的android:configChanges屬性來處理就可以。對於任何配置改變,你會接收到當前Activity的onConfigurationChanged(Configuration)方法調用而不是重啓。如果一個配置改變調用牽涉到任何你不處理的東西,Activity仍然會重啓而不調用onConfigurationChanged(Configuration)。


Starting Activities and Getting Results

The startActivity(Intent) method is used to start a new activity, which will be placed at the top of the activity stack. It takes a single argument, an Intent, which describes the activity to be executed.
startActivity(Intent)方法用來打開一個新的Activity,放在Activity棧頂。它只使用單一變量,一個描述等待被執行的Activity的Intent。

Sometimes you want to get a result back from an activity when it ends. For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected. To do this, you call the startActivityForResult(Intent, int) version with a second integer parameter identifying the call. The result will come back through your onActivityResult(int, int, Intent) method.
有時候你想要從一個Activity的結束獲得一個結果。例如,你可能打開一個Activity讓用戶從聯繫人列表裏選一個人;當選擇結束的時候,會返回被選擇的人。爲此,你可以調用startActivityForResult(Intent,int)第二個整數型參數辨識調用者。通過onActivityResult(int,int,Intent)方法會返回結果。

When an activity exits, it can call setResult(int) to return data back to its parent. It must always supply a result code, which can be the standard results RESULT_CANCELED, RESULT_OK, or any custom values starting at RESULT_FIRST_USER. In addition, it can optionally return back an Intent containing any additional data it wants. All of this information appears back on the parent’s Activity.onActivityResult(), along with the integer identifier it originally supplied.
當一個Activity退出時,它會調用setResult(int)來返回數據給父親。它總是必須提供一個結果碼,可以是標準的結果 RESULT_CANCELED,RESULT_OK,或者任何從RESULT_FIRST_USER 開始的自定義的值。另外,可以有選擇地返回一個Intent,用來含括任何額外的數據。所有的這些信息會出現在回退到父親Activity.onActivityResult()方法,順着它原本提供的整數定義。

If a child activity fails for any reason (such as crashing), the parent activity will receive a result with the code RESULT_CANCELED.
如果一個孩子Activity因爲任何理由(比如崩潰)失敗,父親Activity會接收到一個返回值RESULT_CANCELED。

public class MyActivity extends Activity {
     ...

     static final int PICK_CONTACT_REQUEST = 0;

     public boolean onKeyDown(int keyCode, KeyEvent event) {
         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
  // When the user center presses, let them pick a contact.
             startActivityForResult(
                 new Intent(Intent.ACTION_PICK,
                 new Uri("content://contacts")),
                 PICK_CONTACT_REQUEST);
            return true;
         }
         return false;
     }

     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         if (requestCode == PICK_CONTACT_REQUEST) {
             if (resultCode == RESULT_OK) {
     // A contact was picked.  Here we will just display it
                 // to the user.
                 startActivity(new Intent(Intent.ACTION_VIEW, data));
             }
         }
     }
 }

Saving Persistent State

There are generally two kinds of persistent state than an activity will deal with: shared document-like data (typically stored in a SQLite database using a content provider) and internal state such as user preferences.
通常有兩種方式進行持久化,SQLite和SharedPreferences。

For content provider data, we suggest that activities use a “edit in place” user model. That is, any edits a user makes are effectively made immediately without requiring an additional confirmation step. Supporting this model is generally a simple matter of following two rules:
對於ContentProvider數據,我們建議Activity使用“適當編輯”用戶模型。也就是說,任何的用戶編輯是高效即時不需要請求額外確認步驟的。支持這種模型通常只需要依據以下兩條規則:

When creating a new document, the backing database entry or file for it is created immediately. For example, if the user chooses to write a new e-mail, a new entry for that e-mail is created as soon as they start entering data, so that if they go to any other activity after that point this e-mail will now appear in the list of drafts.
當創建一個文件時,後臺數據庫實體或者文件的創建是即時的。例如,如果一個用戶選擇寫一封新的e-mail,一個新的e-mail實體在它們開始輸入數據的時候就創建了,因此如果它們在這個時間點切換去任何其他Activity時,這封e-mail將出現在草稿箱。

When an activity’s onPause() method is called, it should commit to the backing content provider or file any changes the user has made. This ensures that those changes will be seen by any other activity that is about to run. You will probably want to commit your data even more aggressively at key times during your activity’s lifecycle: for example before starting a new activity, before finishing your own activity, when the user switches between input fields, etc.
當一個Activity的onPause()方法被調用,它應該提交到後臺ContentProvider或者文件關於用戶做了的任何改變。這個確保了那些改變將會被任何其他將要運行的Activity看到。你甚至可能會想要更加粗暴地提交你的數據,在你的Activity生命週期這些關鍵時間點,例如打開一個Activity之前,結束原有Activity之前,當用戶改變輸入域時,等等。

This model is designed to prevent data loss when a user is navigating between activities, and allows the system to safely kill an activity (because system resources are needed somewhere else) at any time after it has been paused. Note this implies that the user pressing BACK from your activity does not mean “cancel” – it means to leave the activity with its current contents saved away. Canceling edits in an activity must be provided through some other mechanism, such as an explicit “revert” or “undo” option.
這個模型的設計是爲了用戶在Activity間操作時防止數據丟失,並且允許系統在Activity已經paused後任何時候安全地幹掉Activity(因爲系統資源在別的地方需要)。這暗示着用戶在Activity按BACK不意味着“取消” – 意味着保存當前內容並離開Activity。Activity必須通過一些其他機制提供取消編輯,例如一個明確的“恢復”或“撤銷”操作。

See the content package for more information about content providers. These are a key aspect of how different activities invoke and propagate data between themselves.
查看content包來獲取更多關於ContentProvider信息。有關鍵的一點是不同Activity之間如何調用和傳送數據。

The Activity class also provides an API for managing internal persistent state associated with an activity. This can be used, for example, to remember the user’s preferred initial display in a calendar (day view or week view) or the user’s default home page in a web browser.
Activity類同樣提供一個API來管理關聯着Activity的內部持久化。舉個例子,爲了記住用戶偏好初始化展示一個日曆或者瀏覽器的用戶默認主頁。

Activity persistent state is managed with the method getPreferences(int), allowing you to retrieve and modify a set of name/value pairs associated with the activity. To use preferences that are shared across multiple application components (activities, receivers, services, providers), you can use the underlying Context.getSharedPreferences() method to retrieve a preferences object stored under a specific name. (Note that it is not possible to share settings data across application packages – for that you will need a content provider.)
Activity的持久化用getPreferences(int)來管理,允許你檢索和修改關聯Activity的鍵值對。爲了使用preferences在多個應用組件間進行共享(Activity,Receiver,Servies,Provider),你可以使用潛在的Context.getSharedPreferences()方法來檢索一個preferences對象來保存在特定名字下。(要注意的是,不可能分享設置數據到不同的應用 – 除非你使用ContentProvider。)

Here is an excerpt from a calendar activity that stores the user’s preferred view mode in its persistent settings:
這裏是一個日曆Activity的摘要,用來保存用戶偏好的識圖模式在它的持久化設置裏:

 public class CalendarActivity extends Activity {
     ...

     static final int DAY_VIEW_MODE = 0;
     static final int WEEK_VIEW_MODE = 1;

     private SharedPreferences mPrefs;
     private int mCurViewMode;

     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         SharedPreferences mPrefs = getSharedPreferences();
         mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
     }

     protected void onPause() {
         super.onPause();

         SharedPreferences.Editor ed = mPrefs.edit();
         ed.putInt("view_mode", mCurViewMode);
         ed.commit();
     }
 }

Permissions

The ability to start a particular Activity can be enforced when it is declared in its manifest’s tag. By doing so, other applications will need to declare a corresponding element in their own manifest to be able to start that activity.
聲明在manifest的標籤裏的Activity能力會被使用。通過在這裏設置,其他的應用需要設置關聯的元素在它們特定的manifest裏才能啓用這個Activity。

When starting an Activity you can set Intent.FLAG_GRANT_READ_URI_PERMISSION and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION on the Intent. This will grant the Activity access to the specific URIs in the Intent. Access will remain until the Activity has finished (it will remain across the hosting process being killed and other temporary destruction). As of GINGERBREAD, if the Activity was already created and a new Intent is being delivered to onNewIntent(Intent), any newly granted URI permissions will be added to the existing ones it holds.
當打開一個Activity時你會設置Intent.FLAG_GRANT_READ_URI_PERMISSION 和/或Intent.FLAG_GRANT_WRITE_URI_PERMISSION 在Intent上。這會授予Activity訪問特別的URI。訪問權會維持到Activity結束(它會維持到持有的進程被幹掉和其他臨時的毀滅)。從Android 2.3起,如果Activity已經被創建並且一個新的Intent正被傳送到onNewIntent(Intent),任何最近的授予的URI權限將被添加到存在的一個Activity上。

See the Security and Permissions document for more information on permissions and security in general.
查看Security和Permissions文檔來獲取更多關於權限和安全的信息。


Process Lifecycle

The Android system attempts to keep application process around for as long as possible, but eventually will need to remove old processes when memory runs low. As described in Activity Lifecycle, the decision about which process to remove is intimately tied to the state of the user’s interaction with it. In general, there are four states a process can be in based on the activities running in it, listed here in order of importance. The system will kill less important processes (the last ones) before it resorts to killing more important processes (the first ones).
安卓系統嘗試儘可能長地保持應用進程存在,但是最後當內存低時將會移除舊的進程。正如Activity Lifecycle裏講到的,決定哪個進程被幹掉和用戶關聯程度有關。一般來說,Activity有四種狀態,按重要順序排列在下面。系統在幹掉重要性高的進程前會幹掉重要性低的進程(最後一個)。

The foreground activity (the activity at the top of the screen that the user is currently interacting with) is considered the most important. Its process will only be killed as a last resort, if it uses more memory than is available on the device. Generally at this point the device has reached a memory paging state, so this is required in order to keep the user interface responsive.
前臺Activity(在屏幕最頂端的Activity,用戶當前正在交互的)被認爲是重要性最高的。它的進程最後纔會被殺,如果要使用的內存比留下的更多時。通常來說這時設備是要即時響應用戶的。

A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog) is considered extremely important and will not be killed unless that is required to keep the foreground activity running.
可見Activity(Activity對用戶來說可見但是不在前臺,例如在一個前臺對話框後面)被認爲是極其重要的並且不會被幹掉除非要保持前臺Activity運行而逼不得已。

A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left it.
後臺Activity(對用戶來說不可見而且已經處於paused)不再危險,所以系統可能會安全地幹掉它的進程來回收利用內存給其他後臺或可見的進程使用。如果它被幹掉,當用戶回到這個Activity時,Activity會通過onSaveInstanceState(Bundle)保存的數據,重新調用onCreate(Bundle)方法來重啓並且恢復到原本狀態。

An empty process is one hosting no activities or other application components (such as Service or BroadcastReceiver classes). These are killed very quickly by the system as memory becomes low. For this reason, any background operation you do outside of an activity must be executed in the context of an activity BroadcastReceiver or Service to ensure that the system knows it needs to keep your process around.
一個空進程是指不持有Activity和其他應用組件(例如Service或BroadcastReceiver類)。這些在系統內存低時會很快被幹掉。因此,任何在Activity之外的後臺操作必須在Activity的BroadcastReceiver或者Service的context執行,來確保系統知道它需要保持你的進程。

Sometimes an Activity may need to do a long-running operation that exists independently of the activity lifecycle itself. An example may be a camera application that allows you to upload a picture to a web site. The upload may take a long time, and the application should allow the user to leave the application while it is executing. To accomplish this, your Activity should start a Service in which the upload takes place. This allows the system to properly prioritize your process (considering it to be more important than other non-visible applications) for the duration of the upload, independent of whether the original activity is paused, stopped, or finished.
有時候,Activity可能需要獨立於生命週期之外做一些長時間運行的操作。一個例子是,一個相機應用允許你上傳照片到網站。上傳可能要耗大量時間,而且應用應該允許用戶在它上傳的時候離開。爲了完成這個,你的Activity應該開啓一個Service來代替Activity上傳。這個允許系統適當地給你的進程在上傳期間排優先級(比其他不可見的應用具有更高的重要性),獨立於Activity原始的paused,stopped或者finished。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章