Android process and thread explanation

Source: Internet
Author: User

As we all know, the process in the operating system is the smallest unit of OS allocated resources, and the thread is the smallest unit to perform the task. A process can have multiple threads to perform tasks that can share the resources that the process assigns to. When our app starts running and no other components are running, the Android system launches a new Linux process to run the app, which contains only one thread running. By default, the components of the app are running in that process, and the thread that originally contained it is also known as the main or UI thread. If we launch the app, there is already a process running the app's component in the system, and the app will run in that process. Of course, we can also make different components in the app run in different processes, or you can perform tasks in any process with new threads.

Process

As mentioned earlier, all components of the same app are running in the same process by default, and most apps don't need to change this setting. But if we really need to specify a process to run a particular component, you can set it in the manifest file. We define various components in the manifest file, such as Activity,service,receiver,provider and so on, and we can set the process property to specify a new thread to run the component. By setting the Process property, we can set each component to run in a different process, or you can specify several components to run in the same process. We can even set up different components from the app to run in the same process (by specifying the same procedure property and sharing the same user ID).

As mentioned in the previous article, the Android system starts a zygote process after it loads the code and resources of the generic framework. In order to start a new program process, the system will fork the zygote process to generate a new process and then load and run the application's code in the new process. This allows most of the RAM pages to be allocated to the framework's code, while allowing RAM resources to be shared across all processes in the app.

The Android system kills some processes in case of low memory to satisfy those processes that interact directly with the user, and the components that run in these killed processes are also logged off. The thread is started when these components are re-run. So, how will the system decide which process to kill? The Android system needs to be judged based on the relevance of the process to the user. For example, compared to the processes that are showing activity, the system is more inclined to kill the processes that are no longer showing activity.

Process life cycle

The Android system will keep a process running for as long as possible, but will eventually reclaim the memory space of the old process for use in new processes or more important processes. The Android system uses a policy that is based on the process of component running and the "importance level" of the component state, and cleans up the process by layer by importance.

The level of importance from high to low is divided into 5 tiers:

1, the foreground process foreground processes

The process that is currently interacting with the user. If a process p satisfies any of the following conditions, the process p is called the foreground process:

    • Activity that is currently interacting with the user (calling the Resume method) runs in process p
    • A service is bound to the activity that is currently interacting with the user, and the service runs in process p
    • A service called the Startforeground () method, which runs in process p
    • A service is executing a callback method for a life cycle that runs in process p
    • A broadcastreceiver is executing its onreceive function, and the broadcastreceiver is running in process p

Typically, only a few of the foreground processes exist at some point in the system. They will only be killed when the memory is very low, in which case the device reaches the "Memory paging state" and only kills some foreground processes to ensure the system responds quickly.

2. Visible processes visable Process

There is no foreground component running in this process, but it can still affect the screen that the user sees. Process P is called a visible process if the process P satisfies any of the following conditions:

    • An activity does not run in the foreground, but is still visible to the user (called the Pause method), and the activity runs in process p. For example, an activity that initiates a dialog can still see the activity.
    • If a service is bound to the visible activity or foreground activity, the service runs in process p.

Visible processes are relatively important, but in some cases the system will kill these visible processes in order to ensure that the foreground process is running.

3. Service Process

If a service is started by the StartService method and is not part of the above two higher-level scenarios, the process that runs the service is called service process. Although the service is not bound to any component that can be seen by the user, the work they do is of interest to the user, such as music playback, file downloads, and so on.

4. Background processes background Process

An activity that is currently not visible (callback the OnStop method) runs on that thread. Such threads cannot directly affect the user experience, and the system may kill such processes at any time to reclaim memory for use by the three processes above. Typically, there are multiple background processes running in the system, so they are stored in an LRU list, so that processes that are least frequently used by users are killed first. If an activity normally callbacks its life cycle functions and stores the corresponding state data, killing the background process will not affect the user experience. Because when the user tries to return to the activity, the system resumes all state of the activity.

5. Empty process

No components are running in the process, and the only reason to keep such processes present is to wait for the task. Once a component needs to run, it can shorten the process startup time. So the system often kills these processes to balance the system resources between the process cache and the underlying kernel cache.

In an Android system, the level of a process can be dynamically boosted, because other processes may depend on the process. A process that provides services to other processes, the level of the process must not be lower than the process it serves. For example, a content provider runs in process a that serves client B in process B, or if the service in process A is bound to a component that is located in process B, the critical level of a process is only higher or equal to process B.

Because a process that runs a service is more hierarchical than those that run in the background activity, if we need to have a long time to perform the operation, It is better to start a service from an activity to accomplish these operations than to open a new child thread in the activity (especially if the child threads have a longer duration than the activity). For example, if an activity wants to upload an image to the server, it should open a service in the background to complete the upload operation, even if the user leaves the current activity, these operations can be completed in the background. Using service guarantees that these operations have at least a service priority, regardless of whether the state of the current activity has changed. This is why broadcast receiver should use service instead of simply putting time-consuming operations on child threads.

Thread

When the application starts, a main thread is created to run the application. The main thread is very important and it is responsible for distributing tasks and events for the appropriate user control, including drawing tasks, and so on. At the same time, the main thread is responsible for interacting with the UI components and applications, so we also call the main thread the UI thread.

The system does not run a single thread for each component, and all components are initialized and run in the same process in the main thread, and each component is called by the system through the main thread. Therefore, system callback methods (such as onkeydown, life cycle callback methods, and so on) typically run on the main thread.

For example, when a user taps a button on the screen, the UI thread distributes the click event to the control. The control sets its own pressed state and adds the redraw request to the event request queue. After the UI thread removes the redraw request from the event queue, notifies the control to redraw.

When users and apps interact frequently, single-threaded patterns can cause slow response times and unsatisfactory user experience. A time-consuming operation such as network or database requests in the main thread can cause the thread to block, and the main thread will not be able to dispatch events and tasks. When more than 5s of blocking causes the system to eject the ANR window. Also, UI controls are not thread-safe, so the system specifies that controls can be modified only in the UI thread. We need to follow two rules:

    1. Do not block the UI thread
    2. Do not modify controls outside the UI thread
Worker thread

This is where only the UI thread works. In order to improve the responsiveness of the application UI and get a better user experience, we need to put the time-consuming action on the child thread. However, it is important to note that you do not manipulate UI controls in child threads. We usually use the Android handler mechanism to solve the problem of inter-thread communication, see the previous article on the asynchronous communication mechanism between Android threads source code analysis. At the same time, Android also provides an async task to complete the asynchronous task.

Asynchronous Task Async Task

The async task executes the time-consuming task in the child thread, and then returns the result to the UI thread without having to manually create the handler itself. The use of async tasks is not described here, and in the process of using async task, we need to be aware of multithreading issues. Problems with running configurations, such as changes in the screen orientation, cause the child thread task to restart execution without our permission.

Thread-Safe methods

In most cases, our approach is likely to be called by multiple threads, so we have to take into account thread safety issues. This is especially true for methods that can be called remotely, such as the method of binding a service. When we try to invoke a method implemented in IBinder, if the caller and IBinder are in the same process, then the method executes in the caller's thread. If the caller is not in the same process as IBinder, the system takes a thread from the pool of maintained threads to execute the method, and the thread pool runs in the same process as ibinder (not in the UI thread). For a chestnut, although the UI thread of the service's process will invoke the service's Onbind method, those implemented in the IBinder object returned by the Onbind method are executed by thread pool threads. Because a service can be accessed by multiple clients, multiple threads in the thread pool can call the same method at the same time. Therefore, the methods implemented in the IBinder object need to be thread-safe.

Similarly, a contentprovider can receive data requests from different processes, although the CP and CR classes hide the details of interprocess communication management, but the corresponding query, delete, modify, insert, and other request methods in the CP will be delivered to the thread pool threads of the process where the CP is located. These methods may be called by multiple processes at the same time, so these methods must be thread-safe.

Inter-process communication

The Android system provides a remote call to RPC mechanism to complete the process communication IPC, through the RPC mechanism, the component in the application (for example, activity) calls a method locally, which executes in a remote (another process) and then returns the result to the caller. This requires that the calling method and its data be resolved to a level that the operating system can understand, and then reorganized and executed after it is passed from the local process and address space to the remote process and address space.

Android process and thread explanation

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.