Android Development-api Guide-processes and Threads

Source: Internet
Author: User

Processes and Threads

English Original: http://developer.android.com/guide/components/processes-and-threads.html
Acquisition (update) Date: 2014-12-25
Moved from the original blog: http://blog.sina.com.cn/s/blog_48d491300100zjpb.html

In this article
    1. Process
      1. The life cycle of a process
    2. Thread
      1. Worker threads
      2. Thread-Safe methods
    3. Inter-process communication

If an application component is started for the first time and no other components are running on the application, the Android system creates a Linux process for the application that contains a single running thread. By default, all components of the same application run in a process and line thread (called the main thread "main"). If the application already has a process when the component starts (because other components of the application are already running), the component starts in the existing process and uses the same running thread. However, you can have different components in one application running in their own separate processes, or you can create more threads for any process.

This article discusses how processes and threads work in Android applications.

Process

By default, all components in the same application run in one process, and most applications do not change this way. However, if you need to specify the process to which a particular component belongs, you can use the Manifest file to achieve the purpose.

The nodes of each component element in the Manifest file-- <activity> , <service> , <receiver> and <provider> --support the android:process definition of the attribute, which specifies the process that runs the component. Setting this property enables different components to run in their own processes, or some components share a process while other components run in their own processes. Setting this property also allows components of different applications to run in the same process-implementing multiple applications that are common to the same Linux user ID and have the same identity signature.

<application>element also supports android:process attributes that specify the default process for all components in the app.

When memory is low, other processes that provide more emergency services to the user require more memory, and the Android system may decide to close a process. Application components that are running in this process are also destroyed. When these components need to work again, a process is recreated for them.

When deciding which process to kill, the Android system weighs how important they are relative to the user. For example, it is more likely to close a process that the activity is already invisible on the screen relative to a process with visible activity. That is, whether to terminate a process depends on the state of the component in which it is running. Subsequent chapters will describe the decision rules for terminating the process.

The life cycle of a process

The Android system preserves the process of an application as long as possible, but in order to create new or run more important processes, it is always necessary to purge obsolete processes in order to reclaim memory. To determine which process to keep or kill, the system includes each process in an "important level list (importance hierarchy)", depending on the components running within the process and the state of those components. When a system resource must be reclaimed, the least important process is purged first, then the next lowest, and so on.

The list of important levels has a total of 5 levels, and the following list lists the various processes by importance (the first type of process is the most important and will be terminated at the end ):

  1. Foreground process

    The process required for the user's current operation. A process is considered to be in the foreground when either of the following conditions is true:

    • One of the methods in which the user is interacting Activity ( Activity the onResume() method that has been called) is running.
    • The object in which it is running is Service bound by the Activity that is interacting with the user.
    • The method in which the "foreground" object is running Service -the service- startForeground() has been called.
    • It runs an object that is executing a lifecycle callback method ( onCreate() , onStart() or onDestroy() ) Service .
    • The object on which the method is executing is running onReceive() BroadcastReceiver .

    In general, there are few foreground processes at any one time. They are only terminated when there is no other way-the memory is not enough to keep them running at the same time. Typically, this time the device has reached the point of using virtual memory (memory paging), terminating some foreground processes to ensure a timely response from the user interface.

  2. Visible process

    Processes that do not contain foreground components, but still affect what users see on the screen. A process is considered a visible process when either of the following conditions is true:

    • It runs an object that is not in the foreground Activity , but the user is still visible to the Activity ( onPause() the method is called). This can happen on the following occasions: The foreground Activity opens a dialog box, and the previous activity also appears under the dialog box.
    • Which is running a visible (or foreground) Activity boundService

    A visible process is considered a very important process, and will not be terminated unless the entire foreground process is maintained.

  3. Service process

    In such a process startService() , a service started by the method is run, and it does not escalate to the previous two levels of importance. Although service processes are not directly associated with what the user sees, they are typically performing actions that are of interest to the user (such as playing music in the background or downloading data from the network). Therefore, the system keeps the service process running unless the memory is insufficient to maintain the full foreground and the visible process running concurrently.

  4. Background process

    A process that contains activity that is not visible to the current user (the method of the Activity object onStop() has been called). These processes have no direct impact on the user experience, and the system may kill them at any time to reclaim memory for use by foreground processes, visible processes, and service processes. There are often many background processes running, so they are stored in an LRU (least recently used) list to ensure that the last Activity that was recently used by the user is killed. If an Activity correctly implements the lifecycle method and saves the current state, terminating such a process does not have a visible impact on the user experience. Because the Activity restores all visible states when the user returns. For more information about save and restore status, see the Activity documentation.

  5. Empty process

    Processes that do not contain any active app components. The only purpose of preserving such a process is to use it as a cache to improve the startup performance of the next component running in this process. In order to balance the overall system resources between the process cache and the kernel cache, the system often kills this process.

Depending on the importance of the current active component in the process, Android will evaluate the process to a level that is as high as possible. For example, if a process is running a service and a user-visible Activity, the process is designated as visible, not a service process.

In addition, the level of a process can be enhanced by the dependency of other processes-the process level that provides services to other processes is never lower than the process that uses the service. For example, if the Content Provider in a process serves the client in process B, or if the service in process A is called by a component in process B, the a process is considered to be at least as important as process B.

Because the level of the process in which the service is located is higher than that of the background activity, if an activity needs to start a long-running operation, it is better to start a service for it than simply create a worker thread-especially if the operation lasts longer than the activity The lifetime of itself is longer. For example, an Activity that uploads images to a Web site should create a service to perform the upload task. This way, even if the user leaves the Activity, the upload will continue to run in the background. Regardless of the state of the Activity, using the service guarantees that the operation has at least the level of the service process. For the same reason, the broadcast receiver (broadcast receiver) should also use the service to handle time-consuming tasks rather than simply putting the task into the thread.

Thread

When the application starts, a running thread named "main" is created for it. The main thread is important because it is responsible for distributing events to the appropriate user interface parts (widgets), including screen drawing events. It is also a thread that the application interacts with the Android UI component package (from the Android.widget and Android.view packages). Therefore, the main thread is sometimes called the UI thread.

The system does not create separate threads for each instance of the component. All components running in the same process are instantiated in the UI thread, and system calls to each component are also distributed by the UI thread. Therefore, methods that respond to system callbacks, such as reporting user actions onKeyDown() or life cycle callback methods, are always running in the UI thread.

For example, when a user touches a button on the screen, the application's UI thread will distribute the touch event to the widget, the widget first puts itself in the pressed state, and then sends a request to the event queue where the display area is invalidated (invalidate). The UI thread pulls this request out of the queue and notifies the widget that it needs to refresh (redraw) itself.

Single-threaded mode can make performance very low unless the application is designed to interact with the user and run heavy tasks. Especially when the UI thread is working on all tasks, those long-consuming operations-such as accessing the network or querying the database-will freeze all the user interfaces. Once the UI thread is blocked, all events cannot be distributed, including screen drawing events. In the eyes of the user, the application is like being suspended. Even worse, if the UI thread is blocked for more than a certain amount of time (currently about 5 seconds), the user will see the infamous Application Stop Response (ANR) dialog box. If the user is dissatisfied, he may quit and delete the application.

In addition, the UI component package for andoid is not thread-safe. Therefore, operating from a worker thread is not allowed ui--can only complete all user interface actions from the UI thread. This way, the single-threaded mode of andoid has only two rules:

    1. Do not block the UI thread.
    2. Do not access the Andoid UI component package outside of the UI thread.
Worker threads

According to the above description of single-threaded mode, to ensure the responsiveness of the program interface, the key is not to block the UI thread. If the operations do not complete quickly, you should let them run on separate line approached ("background" or "work" threads).

For example: Here is a partial code for the Click Listener (Listener), which implements downloading the picture in a standalone thread and displaying it in ImageView :

 PublicvoidOnClick(Viewv){
NewThread(NewRunnable(){
PublicvoidRun(){
Bitmapb=loadimagefromnetwork("Http://example.com/image.png");
Mimageview.Setimagebitmap(b);
}
}).Start();
}

At first glance, this code seems to work well, because a new thread is created to handle the operation of accessing the network. But this violates the second rule of single-threaded mode: Do not access the Andoid UI component package outside the UI thread-the above example is modified in the work line thread instead of the UI ImageView . This can lead to ambiguous and unforeseen consequences, and it is also difficult and time-consuming to track down this situation.

To address these issues, Android provides several ways to access the UI thread from other threads. Here are a few ways to do this:

    • Activity.runOnUiThread(Runnable)
    • View.post(Runnable)
    • View.postDelayed(Runnable, long)

For example, you can use View.post(Runnable) the method to correct the above code:

 PublicvoidOnClick(Viewv){
NewThread(NewRunnable(){
PublicvoidRun(){
FinalBitmapBitmap=loadimagefromnetwork("Http://example.com/image.png");
Mimageview.Post(NewRunnable(){
PublicvoidRun(){
Mimageview.Setimagebitmap(Bitmap);
}
});
}
}).Start();
}

Now the code is thread-safe: The operation of the network is done in a separate thread, and ImageView is manipulated in the UI thread.

However, as operations become more complex, such code can become complex and difficult to maintain. To enable more complex interaction processing with worker threads, consider using them in a worker thread Handler to handle messages sent by the UI thread. However, the best scenario might be an extension AsyncTask class, which simplifies the running mode of the worker threads interacting with the UI.

Using Asynctask

AsyncTaskThe ability to implement asynchronous operations on the user interface. It blocks the worker threads and then renders the results in the UI thread, which does not require any further intervention in the thread and handler.

To use an asynchronous task, you must inherit the AsyncTask class and implement doInBackground() a callback method that runs in a pool of background threads. When updating the UI, the method must be implemented onPostExecute() to distribute the results returned by Doinbackground (), since this method runs in the UI thread, so that the UI can be updated safely. It can then be called in the UI thread execute() to run the task. ,

For example, you can use it AsyncTask to implement the above example:

 PublicvoidOnClick(Viewv){
NewDownloadimagetask().Execute("Http://example.com/image.png");
}

PrivateclassDownloadimagetaskextendsAsynctask<String,Void,Bitmap>{
The /** system executes this method in a worker thread
* and pass in the parameters given by Asynctask.execute () */
protectedBitmapDoinbackground(String...URLs){
returnloadimagefromnetwork(URLs[0]);
}

/** System executes this method in the UI thread
* and pass in results returned by Doinbackground () */
protectedvoidOnPostExecute(Bitmapresult){
Mimageview.Setimagebitmap(result);
}
}

Now that the UI is secure, the code is simplified because it splits the task into the completion part of the worker thread and the completion part of the UI thread.

To fully understand the use of this class, you must read AsyncTask the reference documentation. Here's an overview of how it works:

    • You can use generics (generic) to specify the parameter type, progress value type, and result value type for a task.
    • Methods in the worker thread are doInBackground() executed automatically.
    • onPreExecute(), onPostExecute() and onProgressUpdate() both are called in the UI thread.
    • doInBackground()The return value is passed to theonPostExecute()
    • doInBackground()can be called at any time within the publishProgress() UI thread to execute theonProgressUpdate()
    • You can cancel the task at any time and from any thread

Warning: When using a worker thread, another problem that may be encountered is an unexpected restart of the activity caused by changes in the configuration of the runtime (such as a user changing the screen orientation), which may destroy the worker thread. To learn how to maintain task execution in this case, and how to properly cancel a task when the Activity is destroyed, see the source code for the shelves routine.

Thread-Safe methods

At some point, methods may be called by multiple threads, so these methods must be written in a thread-safe manner.

It is for granted that methods that can be called remotely-such as the methods in the Bound service. If the IBinder invocation of a method in the alignment originates inside the process where IBinder is located, then this method is executed in the caller's thread. However, if the call originated in another process, the method would run on a thread approached in the pool of threads (rather than running in the UI thread of the originating process), which is maintained by the system and is in the same process as the IBinder. For example, even if the method of a service onBind() is invoked from the UI thread of the process in which the service is located, Onbind () returns the method in the object (for example, a subclass of the RPC method) that still initiates a call from a thread in the thread pool. Because a service may have multiple clients, multiple thread pools can be associated with the same IBinder method at the same time. Therefore, the IBinder method must implement the code in a thread-safe manner.

Similarly, Content Provider can receive data requests from other processes. Although ContentResolver classes and ContentProvider classes hide the details of interprocess communication Management, the methods of responding to requests in ContentProvider- query() ,, insert() delete() , update() and getType() -are all lines from the process where the Content Provider resides The Cheng initiates the invocation, not from the UI thread of its process. Because these methods may initiate calls from any number of threads at the same time, they must also be implemented as thread-safe.

Inter-process communication

Android uses remote procedure calls (Remotes procedure Call,rpc) to provide an interprocess communication (IPC) mechanism through which methods that are invoked by Activity or other application components are executed remotely (in other processes). All results are returned to the caller. This requires splitting the method call and its data to the extent that the operating system can handle, transferring it from the local process and address space to the remote process and address space, and then reassembling and executing the call in the remote process. The return value after execution is transferred back in reverse. Android has provided all the code needed to execute an IPC transaction, so just focus on defining and implementing RPC programming interfaces.

The application is to be IPC- bindService() bound with a service. For more information, see the services in the development Guide.

Android Development-api Guide-processes and Threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.