Android DOC翻譯—Processes and Threads

來源:互聯網
上載者:User

Processes and Threads

When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution.
By default, all components of the same application run in the same process and thread (called the "main" thread). If an application component starts and there already exists a process for that application (because another component from the application exists),
then the component is started within that process and uses the same thread of execution. However, you can arrange for different components in your application to run in separate processes, and you can create additional threads for any process.

 

當一個APP的組件啟動,並且這個應用沒有任何一個組件已經運行在系統中的時候,那麼Android 就會為這個APP啟動一個新的linux線程來運算。預設的,所有組件運行在同一個線程裡(叫做:主線程)。如果APP的組件啟動或者已經啟動了一個進程,那麼這個組件就會在這個線程中執行。不過,你可以安排APP中不同的組件運行在分散的線程中,並且,也可以在一個進程中建立多個線程。

 

Processes

By default, all components of the same application run in the same process and most applications should not change this. However, if you find that you need to control which process a certain component
belongs to, you can do so in the manifest file.

 

       預設情況下,一個APP的所有組件都要運行在相同的進程中,並且大多數程式都不能改變這個情況。不過,如果你發現,你需要控制一個進程的某些部分,那麼你可以修改manifest 檔案。

 

The manifest entry for each type of component element—<activity>,
<service>, <receiver>, and <provider>—supports an
android:process attribute that can specify a process in which that component should run. You can set this attribute so that each component runs in its own process or so that some components share a process while others do not.  You can also setandroid:process
so that components of different applications run in the same process—provided that the applications share the same Linux user ID and are signed with the same certificates.

 

       manifest中的每一種component ,<activity>,
<service>, <receiver>, and <provider>都有一個android:process 的屬性,指定組件可以在哪個進程中運行,你也可以設定成,“每個組件運行在自己的線程中”或者“當別人不分享時,分享一些進程給別人”或者“讓不同程式的組件運行在同一個進程中”—這需要應用程式提供相同的linux
user ID 並且標示著相同的認證。

 

The <application> element also supports an
android:process attribute, to set a default value that applies to all components.

 

    <application> 這個元素同樣提供了android:process 這個屬性,去對於所有components 的預設值。

 

Android might decide to shut down a process at some point, when memory is low and required by other processes that are more immediately serving the user. Application components running in the process
that's killed are consequently destroyed.  A process is started again for those components when there's again work for them to do.
     

        Android會在記憶體較低時,或者在那些更直接服務使用者的進程(理解為優先順序較高的進程)需要記憶體時,會殺死一些進程。運行在進程中得組件也因此被殺死。一個進程只有當組件再次被啟動時才能開始工作。

 

When deciding which processes to kill, the Android system weighs their relative importance to the user.  For example, it more readily shuts down a process hosting activities that are no longer visible
on screen, compared to a process hosting visible activities. The decision whether to terminate a process, therefore, depends on the state of the components running in that process. The rules used to decide which processes to terminate is discussed below.

 

       當進程被殺死的時候,Android將權衡哪些進程對於系統相對重要。舉例,相比於那些可見的線程,系統更容易刪除那些儲存著Activity的而不再顯示在螢幕上的進程。因此,依靠這些進程中components的狀態。這些規則將決定誰會被終止。

Process lifecycle

The Android system tries to maintain an application process for as long as possible, but eventually needs to remove old processes to reclaim memory for new or more important processes.  To determine
which processes to keep and which to kill, the system places each process into an "importance hierarchy" based on the components running in the process and the state of those components.  Processes with the lowest importance are eliminated first, then those
with the next lowest importance, and so on, as necessary to recover system resources.

 

        Android系統儘可能唱得去保持一個應用程式,但最終,當需要移除舊進程去為新的更重要的進程去回收記憶體的時候,應該覺得,哪個進程被殺死,哪個被儲存,系統這些組件的state很重。優先順序最低的將優先被淘汰,然後是次低級的。。。等等。

 

There are five levels in the importance hierarchy. The following list presents the different types of processes in order of importance (the first process is
most important and iskilled last):

        下面有五個重要的等級,

       1、前台進程(Foreground process):
  使用者當前工作所需要的。一個進程如果滿足下列任何條件被認為是前台進程:正運行著一個正在與使用者互動的活動(Activity對象的onResume()方法已經被調用)。
  寄宿了一個服務,該服務與一個與使用者互動的活動綁定。
  有一個Service對象執行它的生命週期回調(onCreate()、onStart()、onDestroy())。
  有一個BroadcastReceiver對象執行他的onReceive()方法。
  在給定時間內僅有少數的前台進程存在。僅作為最後採取的措施他們才會被殺掉——如果記憶體太低以至於他們不能繼續運行。
 

    

     2、可視進程(Visible process):
  沒有任何前台組件,但是仍然能影響使用者在螢幕上看到東西。一個進程滿足下面任何一個條件都被認為是可視的:  寄宿著一個不是前台的活動,但是它對使用者仍可見(它的onPause()方法已經被調用)。舉例來說,這可能發生在,如果一個前台活動在一個對話方塊(其他進程的)運行之後仍然是可視的,比如IME的彈出時。
  寄宿著一個服務,該服務綁定到一個可視的活動。
  一個可視進程被認為是及其重要的且不會被殺死,除非為了保持前台進程運行。
 

   

    3、服務進程(Service process):

       是一個運行著一個用startService()方法啟動的服務,並且該服務並沒有落入上面2種分類。雖然服務進程沒有直接關係到任何使用者可見的,它們通常做使用者關心的事(諸如在背景播放mp3或者從網路上下載資料),因此系統保持它們運行,除非沒有足夠記憶體來保證所有的前台進程和可視進程。
 

 

    4、後台進程(Background process):

       是一個保持著一個當前對使用者不可視的活動(已經調用Activity對象的onStop()方法)(如果還有除了UI線程外其他線程在運行話,不受影響)。這些進程沒有直接影響使用者體驗,並且可以在任何時候被殺以收回記憶體用於一個前台、可視、服務進程。一般地有很多後台進程運行著,因此它們保持在一個LRU(least recently used,即最近最少使用,如果您學過作業系統的話會覺得它很熟悉,跟記憶體的頁面置換演算法LRU一樣。)列表以確保最近使用最多的活動的進程最後被殺。

  5、空進程(Empty process): 

      是一個沒有保持活躍的應用程式組件的進程。保持這個進程可用的唯一原因是作為一個cache以提高下次啟動組件的速度。系統進程殺死這些進程,以在進程cache和潛在的核心cache之間平衡整個系統資源。

  一個進程的排名因為其他進程依賴它而上升。一個進程服務其它進程,它的排名從不會比它服務的進程低。例如,進程A中的一個內容提供者服務進程B中的一個客戶,或者進程A中的一個服務綁定到進程B中的一個組件,進程A總是被認為比進程B重要。
  因為一個服務進程排名比後台活動的進程排名高,一個活動啟動一個服務來初始化一個長時間運行操作,而不是簡單地衍生一個線程——特別是如果操作很可能會拖垮活動(例如出現ANR)。這方面的例子是在背景播放音樂和上傳相機拍攝的圖片到一個網站。使用服務保證操作至少有“服務進程”的優先順序,無論活動發生什麼情況。

Threads

When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate
user interface widgets, including drawing events. It is also the thread in which your application interacts with components from the Android UI toolkit (components from the
android.widget and android.view packages). As such, the main thread is also sometimes called the UI thread.

        當一個APP被啟動,系統會建立一個線程去執行。叫做“主線程”。這個線程非常重要,因為,這個線程,負責event處理和UI互動,這個線程,也是用來於Android UI toolkit 互動的,因此,主線程有時也被稱為UI線程。

 

     當線程被阻塞,就會出現ANR,所以對於Android 單執行緒模式。

    1.不要阻礙UI線程,

    2.不要在UI線程之外調用UI控制項。

 

Worker threads

 

public void onClick(View v) {    new Thread(new Runnable() {        public void run() {            final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");            mImageView.post(new Runnable() {                public void run() {                    mImageView.setImageBitmap(bitmap);                }            });        }    }).start();}

 

AysncTask

 

AsyncTask  allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker
thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

To use it, you must subclass
AsyncTask and implement the doInBackground() callback method, which runs in a pool of background threads. To update your UI, you should implement
onPostExecute(), which delivers the result from doInBackground() and runs in the UI thread, so you can safely update your UI. You can then run the task by calling
execute()from the UI thread.

      使用AsyncTask ,需要繼承AsyncTask 並且實現 doInBackground() ,通過實現onPostExecute()這個方法來更新UI,可以通過調用execute()這個方法來執行任務。

 

 

public void onClick(View v) {    new DownloadImageTask().execute("http://example.com/image.png");}private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {     /** The system calls this to perform work in a worker thread and      * delivers it the parameters given to AsyncTask.execute() */                  protected Bitmap doInBackground(String... urls) {        return loadImageFromNetwork(urls[0]);    }        /** The system calls this to perform work in the UI thread and delivers      * the result from doInBackground() */    protected void onPostExecute(Bitmap result) {        mImageView.setImageBitmap(result);    }}

 

Thread-safe methods

In some situations, the methods you implement might be called from more than one thread, and therefore must be written to be thread-safe.

       一些情況,我們實現的方法會被很多線程調用,因此,我們要考慮安全執行緒。

 

(剩下的以後翻譯。。。)

This is primarily true for methods that can be called remotely—such as methods in a
bound service. When a call on a method implemented in an
IBinder originates in the same process in which theIBinder is running, the method is executed in the caller's thread.
However, when the call originates in another process, the method is executed in a thread chosen from a pool of threads that the system maintains in the same process as the
IBinder (it's not executed in the UI thread of the process).  For example, whereas a service'sonBind()
method would be called from the UI thread of the service's process, methods implemented in the object that
onBind() returns (for example, a subclass that implements RPC methods) would be called from threads in the pool. Because a service can have more than one client,
more than one pool thread can engage the same IBinder method at the same time. 
IBinder methods must, therefore, be implemented to be thread-safe.

       

 

Similarly, a content provider can receive data requests that originate in other processes. Although the
ContentResolver and
ContentProviderclasses hide the details of how the interprocess communication is managed,
ContentProvider methods that respond to those requests—the methods
query(),
insert(),
delete(),
update(), and
getType()—are called from a pool of threads in the content provider's process, not the UI thread for the process.  Because these methods might be called
from any number of threads at the same time, they too must be implemented to be thread-safe.

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.