"Android Document" Processes and Threads

Source: Internet
Author: User

Take a general translation and take notes.

Original address: Processes and Threads

Processes and Threads

When a component of an app (which is generally referred to as four components activity,service, etc.) starts, if no other components are running at this time, the Android system launches a new Linux process for the app, and there is only one thread in the process. By default, all components in the app run on the same thread (called the main thread) in the same process. If a process already exists in the app when the component of an app is started, the component runs in the same process and uses the same thread of execution. In fact, you can also set up individual components in the same app to run in different processes, and multiple threads can be created in each process.

This document focuses on processes and threads in Android apps (Processes and Threads)


ProcessesBy default, each component in the app runs in the same process, and most apps should follow this rule. Then, if you think you need to specify that a component belongs specifically to a process, you can configure it in the manifest file.
Tags for various components in the manifest file------<activity>, <service>, <receiver>, <provider> support Properties android:process , this property can specify a process for the component. After the component has specified a process of its own with this property, some components will no longer share a process with other components, although some of them still share a process. Even, you can set android:process to make different apps run in the same process------premise is that different apps want to use the Linux User ID and the same signature. (The Android plugin principle seems to involve this point)
The <application> element also supports the android:process attribute, and its scope will be all components.
In Android, when some processes that are serving users require memory, the system will consider shutting down some processes if the system is low on memory at this time. When a process is killed, all components in the process are destroyed. When the component being destroyed restarts, the process in which it resides will also be restarted.
When deciding which process to kill, the Android system will measure the importance of each process to the user. For example, if a process holds multiple activity that is no longer displayed on the screen, the process is most likely to be killed first, and the determinant of killing a process is the state of the component running in that process. The following is a discussion of the rules for choosing which processes to kill.
Process lifecycleThe Android system maintains the app's process as much as possible, but sometimes it has to kill some processes in order to reclaim the memory used to update more important processes. To select a process to kill, the system divides the process into a hierarchy of importance, based on the components in the process and the state of the component. When a system resource needs to be reclaimed, the least important process is killed first and then the other processes are killed in order of importance.
The important grading is divided into 5 levels, and the following lists various processes in terms of importance from high to the end.
1,foreground processThe process in which the user is currently operating is the foreground process. Processes that meet any one of the following conditions are foreground processes.1) The process in which the user is currently interacting (without disappearing and gaining focus)2) A service is bound to the activity that the user is currently interacting with, the process in which the service resides.3) A service runs in the foreground (that is, the service that calls Startforeground (), the process in which the service resides.4) A process executes any one of its lifecycle callback methods (OnCreate (), OnStart (), OnDestroy ()), the processes in which the service resides.5) A process that is executing a broadcastreceiver onreceive () methodTypically, an app will only have a few foreground processes at the same time. When the system's memory is particularly low, the foreground process will not continue to run, killing them to maintain the user UI interface can be normal response, the foreground process is the last to be killed,
2,visible processWhile some processes do not have any foreground components, they can still affect what is displayed on the current screen. This process is a visible process, and components that meet any of the following conditions are visible processes.1) Although an activity is not in the foreground (foreground), it is still visible (visible), generally because the visible precess executes the OnPause method. For example, an activity in the foreground initiates a dialog, at which point the activity changes from the front (foreground) to the visible (visible). This visible activity is in the process of visible precess.2) When a service is bound to an activity of a visible or foreground, the process in which the service resides is the visible precess.The visible precess will not be killed, unless the system is in dire need of recycling resources and must be kept foreground process running, the visible process will have to be killed.
3,service processService process typically runs a startservice ()-initiated service and has not become the top two processes. Although service process is not directly related to the user interface, it is often done with certain user-specific actions, such as playing music or downloading data from the network. The system generally keeps these processes running unless it is necessary to kill them to release resources.
4,background processBackground process has a user currently invisible activity, that is, the activity executes the OnStop method, such as Activitya start Activityb, then Activitya becomes invisible. This process does not have a direct impact on the user interface, and the system kills background process when it needs to reclaim memory for foreground, visible, or service process. Typically, multiple background process runs at the same time, and they are maintained in an LRU (least recently used) queue. This process, which has not been presented to the interface for too long, will be preferentially killed. If the activity properly overrides its life cycle callback method, it will be able to save the data when the process is killed and recover the data when the activity is re-appearing, in which case the user will not feel the process being killed.
5,empty processThere are no active components in Empty process. The purpose of this process is to cache, which can improve the startup time of the next component. The system kills this process generally in order to balance the cache in these processes and the underlying kernel cache. (This sentence is not easy to understand, translation is not good)When a process belongs to more than one of the 5 processes in the process, the Android system classifies it into one of the more important of its kind. For example, if a process has both a service and a visible activity, the process will be categorized into the visible process, not the service process.In addition, the sequencing of a process may rise because of a dependency, for example, if a component in process a relies on a component in process B, then process B cannot have a lower order of importance than process a. At least the importance should be the same.
As mentioned above, we can know that the process of running the service, and the process running the background activity, the former is more important than the latter. So you need to start a time-consuming activity, and this activity is best to start a service to perform that time-consuming operation instead of creating a normal worker thread. Especially when the time-consuming operation is longer than the activity's life cycle. For example, an activity will upload an image, and you can launch a service to upload the image so that the service will continue to run when the user leaves the activity. Using service ensures that the time-consuming operation has at least one service process level of importance. No matter what happens to your activity. In the same vein, we'd better perform time-consuming operations in broadcast receiver by starting a service rather than starting a thread.( the time-consuming operation above if the thread is started, the process of importance of the order can only be "background process", lower than "service process ")
ThreadsWhen an app is launched, a thread is created for the app, called the main thread, which manages event distribution, control interaction, and drawing of controls in the UI interface. The importance of this thread is self-evident. The main thread is sometimes referred to as the UI thread.
The system does not create separate threads for each control (the controls we say here distinguish between the above components, the control here refers to the UI controls). All controls in the same process are in the UI line approached (there is only one UI thread in a process), and the system calls to each control occur in the UI thread. Therefore, the system's callback methods (such as onkeydown (), a method that reflects the user's actions, and a life-cycle callback method) are all running in the UI thread of the process.
For example: When a user presses a button on the screen, the UI thread distributes the touch event to the button control, and then the button control sets its own state to pressed. Then issue a request to the event queue that sets itself to invalidate (which can no longer be pressed). The UI thread processes the request in the queue and notifies the button component to redraw it.
A single-threaded model with a UI thread will have a poor performance when the app is performing some tedious operations on the user's actions, unless you handle it appropriately. A point that needs to be taken, if access to the network, access to the database and other time-consuming operations are performed in the UI thread, will block the entire UI process. When the UI process is blocked, the event cannot be distributed, nor can it be redrawn. From the user's point of view, the app is suspended and paused. When the UI thread is blocked for more than a few seconds (currently the system is set for about 5 seconds), the user will get a notorious "application Not Responding" (ANR) pop-up window. Users are only forced to opt out of the app at this time.
In addition, Android UI controls are not thread-safe, so modifications to the UI component can no longer be done by the worker thread, but the UI controls should be modified in the UI thread. In summary, this single-threaded model of the Android system UI thread has the following two rules:1) cannot block UI thread2) UI controls can no longer be manipulated outside the UI thread.
Worker ThreadsAs the single-threaded model described above, the UI response should not block the UI thread, and when you need to do things that are not short-term, you'd better do it in a separate thread.For example, the following downloads a picture in a click Listener and displays the picture 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, the above code does not seem to be a problem, we create a new thread to handle the network operation. Then it only conforms to the first of the two rules of the single-threaded model mentioned above, not the second--------can only manipulate UI controls in the UI thread. In the above code, we modify ImageView in the worker thread rather than in the UI thread. Because UI controls are not thread-safe, they can cause unpredictable errors.
To solve this problem, the Android system provides several ways to allow other threads to access the UI thread, and here are a few ways to do this:1) activity.runonuithread (Runnable)2) view.post (Runnable)3) view.postdelayed (Runnable, long)To solve the above problem, the above code fragment can be modified to use View.post (Runnable),
public void OnClick (View v) {    new Thread (new Runnable () {public        void run () {            final Bitmap Bitmap = LOADIMAGEF Romnetwork ("Http://example.com/image.png");            Mimageview.post (New Runnable () {public                void run () {                    mimageview.setimagebitmap (bitmap);}}            );    } ). Start ();}

Now, the Caffrey fragment above is thread-safe, network access is performed in a separate thread, and ImageView is modified in the UI thread.
Then, as the logic code for the time-consuming operation becomes complex, the coding style above becomes complex and difficult to maintain. In order to handle complex code in the worker thread, you can use Handler,handler in the worker thread to handle messages that are distributed from the UI thread. However, the best way to do this is to use Asynctas, Asynctas can greatly simplify the code when the worker thread needs to interact with the UI thread.

Using AsynctaskAsynctask's role is to allow you to perform asynchronous tasks on the UI interface. It takes the blocking process to schedule the worker thread to execute, and publishes the execution results to the UI thread, and does not require you to handle the above thread and handler issues yourself.
With Asynctask, you need to implement a asynctask subclass and implement the Doinbackground () callback method in it, which runs in a thread pool in the background. In order to update the UI, you need to implement the OnPostExecute () method that receives the results from Doinbackground () and that the method is running in the UI thread, all of which you can safely update the UI interface in OnPostExecute (). Asynctask is initiated by calling its execute () method in the UI thread.
The following is an example of updating ImageView with the above download image via Asynctask.

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 W Ork in a worker thread and      * delivers it the parameters given to Asynctask.execute () */    protected Bitmap doinbackg Round (String ... URLs) {        return loadimagefromnetwork (Urls[0]);    }        /** The system calls the perform work in the UI thread and delivers      * The result from doinbackground () */    Prot ected void OnPostExecute (Bitmap result) {        mimageview.setimagebitmap (result);}    }


The code is thread-safe, and the code looks much more concise because it splits the workers thread and the tasks that need to be done in the UI thread.
If you want a more in-depth understanding, you can read the Asynctask API documentation. The main points of Asynctask are outlined below.
1) You can define the type of the parameter, the progress value, and the result value of the task by generic type. 2) Doinbackground () automatically executes in a worker thread 3) OnPreExecute (), OnPostExecute (), and Onprogressupdate () Execute 4 in the UI thread) Doinbackground () execution results are sent to OnPostExecute () 5) You can call Publishprogress () at any time at Doinbackground (), The method calls Onprogressupdate (), and Onprogressupdate () is executed in the UI thread. 6) You can cancel Asynctask at any time in any thread.

It is important to note that when the system changes at run time, such as screen rotation, the worker thread may be forced to restart. As for how to properly maintain thread tasks before and after a reboot, and how to properly terminate the thread when the activity is destroyed, refer to the shelves example

Thread-safe methods This knowledge point temporarily use not much, understand limited, later development used to read the paragraph in detail

Interprocess COMMUNICATIONIPC, this knowledge point temporarily use not much, understand limited, later development used to read the paragraph in detail

"Android Document" Processes and Threads

Related Article

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.