首页 > 代码库 > 2.App Components-Processes and Threads

2.App Components-Processes and Threads

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

2. Processes

  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 also set android: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.

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

    The following list presents the different types of processes in order of importance (the first process is most important and is killed last):

    <1> Foreground process

        A process that is required for what the user is currently doing

    <2> Visible process

        A process that doesn‘t have any foreground components, but still can affect what the user sees on screen.(onPause)

    <3> Service process

        startService()

    <4> Background process

        onStop()

    <5> Empty process

 

3. Threads

  Threre are simply two rules to Android‘s single thread model:

  <1> Do not block the UI thread

  <2> Do not access the Android UI toolkit from  outside the UI thread

  3.1 Worker threads

    For example, below is some code for a click listener that downloads an image from a separate thread and displays it in an ImageView: 

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

    At first, this seems to work fine, because it creates a new thread to handle the network operation. However, it violates the second

      rule of the single-threaded model: do not access the Android UI toolkit from outside the UI thread—this sample modifies the

      ImageView from the worker thread instead of the UI thread. This can result in undefined and unexpected behavior, which can be

      difficult and time-consuming to track down

    To handle more complex interactions with a worker thread, you might consider using a Handler in your worker thread, to process

      messages delivered from the UI thread. Perhaps the best solution, though, is to extend the AsyncTask class, which simplifies the

      execution of worker thread tasks that need to interact with the UI.

  3.2 Using AsyncTask

    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.

    For example, you can implement the previous example using AsyncTask this way:

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);    }}

 

4. 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 the IBinder 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‘s

    onBind() 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 ContentProvider

    classes 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. Interprocess Communication

  Android offers a mechanism for interprocess communication (IPC) using remote procedure calls (RPCs), in which a method is called by an

    activity or other application component, but executed remotely (in another process), with any result returned back to the caller. This

    entails decomposing a method call and its data to a level the operating system can understand, transmitting it from the local process

    and address space to the remote process and address space, then reassembling and reenacting the call there. Return values are then

      transmitted in the opposite direction. Android provides all the code to perform these IPC transactions, so you can focus on defining

    and implementing the RPC programming interface.

  To perform IPC, your application must bind to a service, using bindService().

    

2.App Components-Processes and Threads