Android process and thread

Source: Internet
Author: User

Processes and threads

If an application component is started for the first time and no other components are running in the application, the Android system will create a linux Process containing a single thread for the application. By default, all components of the same application run in the same process and thread (called "main" main thread ). If the application process already exists when the component is started (because other components of the application are already running), the component starts to run in the existing process and thread. However, you can specify that the component runs in another process or create additional threads for any process.

This article discusses how processes and threads play a role in Android applications.

 

Process

By default, all components in the same application run in the same process, and most applications do not change it. However, you can use the manifest file to specify the process to which a specific component belongs.

Each component element in the manifest file, including <activity>, <service>, <javaser>, and <provider>, supports defining the android: process attribute to specify the processes that the component runs. By setting this attribute, each component can run in its own process, or several components share a process while other components run in independent processes. Setting this attribute allows components of different applications to run in the same process. Multiple applications share the same Linux User ID and grant the same permissions.

The <application> element also supports the android: process attribute to specify the default processes of all components.

If the memory is insufficient, other processes that provide users with more urgent services need more memory, Android may decide to close a process. Application components running in this process will also be destroyed. When you need to work again, a new process will be created for these components.

When deciding which process to close, the Android system will weigh their importance to the user. For example, a process with a visible activity may close a process that is invisible to the screen. That is to say, whether a process is terminated depends on the status of components running in the process. The Determination Rules for terminating processes will be discussed later.

 

Process Lifecycle

The Android system tries to keep the application process as long as possible, but in order to create or run more important processes, it is always necessary to clear outdated processes to recycle the memory. To determine which process to retain or terminate, the system splits each process into an importance hierarchy based on the components running in the process and the status of these components. Processes with the lowest importance will be cleared first, and then the next lowest. Such push is required to recycle system resources.

There are five levels of importance hierarchies. The following list lists various processes by importance (the first type of process is the most important and the last one will be terminated ):

1. Foreground Process

The process required for the current operation. When any of the following conditions is met, the process is considered to be at the front end:

O the Activity that is running with the user interaction (the onResume () method of the Activity object has been called ).

O it runs the Service bound to the activity that is interacting with the user.

O the "front-end" Service-the Service is called in startForeground () mode.

O the Service that is executing the life cycle callback method (onCreate (), onStart (), or onDestroy.

O which runs the BroadcastReceiver that is executing the onReceive () method.

In general, there are only a few front-end processes at any time. They are terminated only when the memory is insufficient to maintain them at the same time. Generally, the device has reached the memory paging state. The frontend processes are terminated to ensure prompt responses to the user interface.

 

2. Visible Process

There is no front-end component, but it still affects the process of what you see on the screen. The process is considered visible when any of the following conditions are met:

O the Activity that is not running in the foreground is displayed, but the onPause () method is called ). For example, this may happen in the following scenarios: the foreground activity opens a dialog box, and the previous activity can be displayed later.

O running the Service bound to the visible (or foreground) activity.

It can be seen that processes are considered very important. They will not be terminated unless they cannot maintain that all foreground processes are running at the same time.

 

3. Service Process

This process runs the service started by the startService () method and is not upgraded to the above two levels. Although service processes are not directly associated with what you see, they generally perform operations that users care about (such as playing music in the background or downloading data from the Internet ). Therefore, unless the memory is insufficient to maintain the running of all foreground and visible processes at the same time, the system will maintain the running of service processes.

 

4. Background Process

The process that contains the currently invisible activity (the onStop () method of the Activity object has been called. These processes have no direct impact on user experience, and the system may terminate them at any time to recycle the memory for foreground processes, visible processes, and service processes. There are usually many background processes running, so they are saved in an LRU (least recently used) list to ensure that the last activity recently used by users is terminated. If an activity correctly implements the lifecycle method and saves the current state, terminating such a process will not have a visible impact on the user experience. Because when the user returns, the activity will restore all visible states. For more information, see Activities.

 

5. Empty Process

Processes that do not contain any active application components. The only purpose of retaining such a process is to use it as a cache to improve the start time of the component running in the process next time. To balance the overall system resources between the process cache and the kernel cache, the system often terminates this process.

 

Based on the importance of the active components in the process, Android evaluates the process to the highest possible level. For example, if a process runs a service and a user-visible activity, the process is evaluated as a visible process rather than a service process.

In addition, the level of a process may be increased due to the dependency of other processes-the process level that provides services for other processes will never be lower than the process that uses this service. For example, if the content provider in process A provides services for the client in process B, or the service in process A is called by the component in process B, process A is considered at least as important as process B.

Because the process level of the running service is higher than that of the background activity process, if the activity needs to start an operation that runs for a long time, it is better to start a service than simply creating a working thread-especially when the operation time is longer than the activity time. For example, if an activity needs to upload images to a Web site, a service should be created for execution. Even if the user leaves the activity, the upload will continue to run in the background. No matter what happens to the activity, you can use the service to ensure that the operation has at least the priority of the "service process. Similarly, the broadcast receiver in the previous article uses services rather than threads to process time-consuming tasks.

 

 

Thread

When the application starts, the system will create a main thread named "main" for it. The main thread is very important because it is responsible for distributing events to corresponding user interface widgets-including Screen Drawing events. It is also the thread in which the application interacts with the Android UI component package (from the android. widget and android. view package. Therefore, the main thread is also called the UI thread.

The system does not create a separate thread for each component instance. 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 for responding to system callbacks (such as onKeyDown () for reporting user operations or lifecycle callback) always run in the UI thread.

For example, when you touch a button on the screen, the UI thread of the application distributes the touch event to the widget. The widget sets itself to the pressed state first, then, send an invalidate request to the event queue. The UI thread retrieves this request from the queue and notifies the widget to redraw itself.

If the application needs to execute heavy tasks while interacting with the user, the single-threaded mode may cause low running performance, unless the application is properly executed. If the UI thread needs to process everything, operations that take a long time, such as accessing the network or querying the database, will block the entire UI (thread ). Once a thread is blocked, all events, including Screen Drawing events, cannot be distributed. From the user's point of view, the application seems to be suspended. What's worse, if the UI thread is blocked for more than a certain period of time (currently about 5 seconds), the user will be prompted for the hateful "ANR" dialog box. If the user is dissatisfied, he may decide to exit and delete the application.

In addition, the Andoid UI component package is not thread-safe. Therefore, you are not allowed to operate the UI from the work thread-you can only operate the user interface from the UI thread. Therefore, the single-thread mode of Andoid must comply with two rules:

1. Do not block the UI thread.

2. do not access the Andoid UI package outside the UI thread.

 

Worker thread

According to the description of the preceding single-thread mode, to ensure the response capability of the program interface, the key is not to block the UI thread. If the operations cannot be completed quickly, run them in a separate thread ("background" or "working" Thread ).

For example, the following code responds to mouse clicks to download images from a separate thread and display them in 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 glance, this code seems to run well, because a new thread is created to process network access operations. However, it violates the second rule of Single-threaded mode: do not access the Andoid UI component package outside the UI thread-the preceding example modifies the ImageView in the working thread rather than in the UI thread. This may lead to unclear and unpredictable consequences. It is very difficult and time-consuming to track this situation.

To solve the preceding problems, Android provides several ways to access the UI thread from other threads. The following lists several methods to help solve the problem:

· Activity. runOnUiThread (Runnable)

· View. post (Runnable)

· View. postDelayed (Runnable, long)

 

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

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

}

The execution of the above Code is now thread-safe: Network-related operations are completed in a separate thread, while ImageView is manipulated in the UI thread.

However, as operations become increasingly complex, such code will become very complex and difficult to maintain. To use a working thread for more complex interaction processing, Handler can be used in the working thread to process messages distributed by the UI thread. Of course, the best solution may be to inherit from the AsyncTask class for asynchronous tasks, which simplifies some operations for interaction between working threads and the UI.

 

Use asynchronous tasks

AsyncTask allows asynchronous operations on the user interface. It first blocks the working thread and then presents the result in the UI thread. In this process, no manual intervention is required on the thread and handler.

To use an asynchronous task, you must inherit the AsyncTask class and implement the doInBackground () callback method. This object runs in a background thread pool. To update the UI, you must implement the onPostExecute () method to distribute the results returned by doInBackground (). Because this method runs in the UI thread, you can safely update the UI. Then you can call execute () in the UI thread to execute the task.

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

Public void onClick (View v ){

New downloadimagetask(cmd.exe cute ("http://example.com/image.png ");

}

 

Private class DownloadImageTask extends AsyncTask <String, Void, Bitmap> {

/** The system callthis to perform work in a worker thread and

* Delivers it the parameters given to AsyncTask.exe cute ()*/

Protected Bitmap doInBackground (String... urls ){

Return loadImageFromNetwork (urls []);

}

/** The system callthis to perform work in the UI thread and delivers

* The result from doInBackground ()*/

Protected void onPostExecute (Bitmap result ){

MImageView. setImageBitmap (result );

}

}

Now the UI is secure and the code is simplified, because the task is divided into the completed part in the working thread and the completed part in the UI thread.

To fully understand the use of this class, read the reference document of AsyncTask. The following is an overview of how it works:

· You can use generics to specify the types of parameters, progress values, and task final values.

· The doInBackground () method in the worker thread is automatically executed.

· The onPreExecute (), onPostExecute (), and onProgressUpdate () methods are all called in the UI thread.

· The Return Value of doInBackground () will be passed to onPostExecute ().

· At any time in doInBackground (), you can call publishProgress () to execute onProgressUpdate () in the UI thread ().

· The task can be canceled at any time and in any thread.

Note: When working threads are used, another problem that may occur is that the activity restarts unexpectedly due to changes in the running configuration (for example, the user changes the screen direction), which may destroy the working thread. To learn how to maintain the task execution in this case, and how to cancel the task correctly when the activity is destroyed, see the source code of the Shelves routine.

 

Thread Security Method

In some cases, methods may be called from more than one thread, so these methods must be written as thread-safe.

For methods that can be remotely called, such as methods in the bound service, this is a matter of course. If the call to the method implemented by IBinder is initiated within the process where IBinder is located, this method is executed in the caller's thread. However, if the call is initiated by another process, this method will run in a thread selected in the thread pool (rather than in the UI thread of the process ), this thread pool is maintained by the system and is located in the process where IBinder is located. For example, even if the onBind () method of a service is called from the UI thread of the process where the service is located, the onBind () method object (for example, A subclass that implements the RPC method) will still be called from the thread in the thread pool. Because a service can have more than one client, multiple thread pools can be associated with the same IBinder method at the same time. Therefore, the IBinder method must be thread-safe.

Similarly, content providers can receive data requests from other processes. Although the ContentResolver and ContentProvider classes hide the details of inter-process communication management, the methods in ContentProvider to respond to requests include query (), insert (), delete (), update () and getType () methods -- called from the thread pool of the process where ContentProvider is located, rather than the UI thread of the process. Because these methods may be called from multiple threads at the same time, they must also be implemented as thread-safe.

 

 

Inter-process communication

Android uses remote procedure call (RPC) to provide an inter-process communication (IPC) mechanism, methods called by activity or other application components will be remotely executed (in other processes), and all results will be returned to the caller. This requires that the method call and its data be decomposed to a level that can be understood by the operating system and transmitted from the local process and address space to the remote process and address space, then re-assemble and execute the call in the remote process. The returned value after execution will be transferred back. Android provides all the code required to execute IPC, so you only need to focus on defining and implementing the RPC programming interface.

Yes

 

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.