RPM: Process and thread Summary for Android

Source: Internet
Author: User

When an Android application component starts, if the other components of the program are not running at this point, the system launches a new Linux process as a single thread for the program. By default, all components under the same application run again in the same process and thread (commonly referred to as the "main" thread of the program). If an application component starts but the process of the application already exists (because the other components of the application have been started before), the component will be launched in this process and executed in the main thread of the application. However, you can also allow components inside your application to run in different processes or add additional threads to any process.

Ad:51cto Net + 12th salon: The beauty of big data-how to drive user experience with data

This article is translated from Android official documentation

When an Android application component starts, if the other components of the program are not running at this point, the system launches a new Linux process as a single thread for the program. By default, all components under the same application run again in the same process and thread (commonly referred to as the "main" thread of the program). If an application component starts but the process of the application already exists (because the other components of the application have been started before), the component will be launched in this process and executed in the main thread of the application. However, you can also allow components inside your application to run in different processes or add additional threads to any process.

This article discusses how the processes and threads inside the Android program work.

Process

By default, all components of the same program run in the same process, and most applications do. However, if you find that you need to have a component inside your program running in a particular process, you can set it up in the manifest file.

The manifest file contains-<activity> for each component element, <service>, <receiver>, and <provider>-provides android:process properties. By setting this property you can have the component run in a particular process. You can set up each component to run in your own process, or you can let some components share a process while others do not. You can also set up components for different applications to run in the same process-allowing these apps to share the same Linux User ID and be certified by the same certificate.

The <application> element also supports the Android:process property, which allows all components in the application to inherit this property by default.

Android may have less memory left in the system, while other direct service users ' processes are shut down a process when they request memory, and the components in this process will be killed in turn. When these components have new tasks to arrive, their corresponding processes are started again.

When deciding which processes need to be killed, the Android system will weigh the importance of these processes with the user. For example, it is easier for the system to kill those processes that carry the activities that are no longer visible, compared to those that carry this visible activities. Deciding whether to end a process depends on the state of the component running within the process. Below we will discuss some of the rules used in the kill process.

The life cycle of a process

As a multi-tasking system, Android system can, of course, keep an application process as long as possible. But because new or more important processes require more memory, the system has to gradually end the old process to get the memory. In order to declare which processes need to be persisted and which require kill, the system generates an "importance level" for each process based on the components within those processes and the state of those components. Processes at the lowest importance level will be clear the first time, followed by a higher point of importance, and so on, depending on the needs of the system to terminate the process.

There are 5 levels in this level of importance. The following list shows the different types of processes in order of importance (the first process is the most important and therefore will be killed at the end):

  1. The Foreground process is a process that is interacting with the user. If a process is in one of the following States, then we can refer to this process as the foreground process:
    • The process contains an activity that interacts with the user (the Onresume () method of the activity is called).
    • The process contains a Service that binds the activity with which the user interacts.
    • The process contains a service-that runs in the foreground state, and the Service calls the Startforeground () method.
    • The process contains a Service that is running its lifecycle callback function (OnCreate (), OnStart (), Orondestroy ()).
    • The process contains a broadcastreceiver that is running the OnReceive () method.

    Generally, there are only a few foreground processes in the system at any one time. The system is only able to kill these processes to relieve memory pressure when the system memory is so intense that it cannot continue to run. At such times the system must kill some (generally, at that point, the device had reached a memory paging state, how do you translate it better) foreground process to ensure that the user's interaction has Response.

  2. Visible process A process does not have any foreground components, but it can also affect the display on the screen. If a process is in one of the following States, then we can refer to this process as the visible process:
    • The process contains an Activity that is not in the foreground state, but it is still visible to the user (its OnPause () method has been called). This can happen, for example, when a foreground activity initiates a dialog, which makes the previous activity visible in the back part of dialog.
    • The process contains a Service that is bound to a visible (or foreground) activity.

    A visible process is quite important in the system and is only considered to kill the visible process in order for all foreground processes to run properly.

  3. The service process is a process that contains a service that has been started with the StartService () method, and has not entered the two higher-level categories above. Although the service process is not directly associated with what any user sees, they are often used to do things that the user cares about (such as playing music in the background or downloading network data), so the system will only be in order to ensure that all foreground and visible Kill the service process when the process is running normally.
  4. The Background process is a process that contains an activity that has not been visible (the activity's OnStop () has been called). Such processes do not directly affect the user's experience, and the system can kill them for foreground, visible, or service processes at any time. In general, there are many background processes running in the system, so keeping them in an LRU (least recently used) list ensures that the activity that the user has recently seen will be killed at the end of the process. If an activity correctly implements its life cycle callback function and saves its current state, then the process of kill will not affect the user's visual experience, because when the user rolls back to the activity, All of its visible states will be restored. View activities can get more documents if you save and restore status.
  5. Empty process a process that does not contain any active application components. The only reason this process exists is caching. In order to increase the start time of a component it is necessary for the component to run in this process. To balance the process cache and the associated kernel cache system resources, the system needs to kill these processes.

Android is rated according to the importance of the components in the process as high as possible. For example, if a process contains a service and a visible activity, the process will be evaluated as the visible process, not the service process.

In addition, a process's rating may be boosted by other processes attached to it-a process that serves other processes is never rated lower than the process it is serving. For example, if a content provider in process A is serving a client in process B, or if a service in process A is bound to a component in process B, process A's rating is considered to be at least higher than process B.

Because the process is running a service rating higher than a process containing background activities, it is a good idea to start a service to do this when an activity initiates a long operation. Instead of simply creating a worker thread-especially when this long-time operation can drag the activity down. For example, an activity that needs to upload an image to a website should open one to perform the upload operation. This way, even if the user leaves the activity, it will ensure that the upload action continues in the background. Using a service ensures that the operation is at least at the service process priority, regardless of what happened to the activity. This is why broadcast receivers should use services rather than simply putting time-consuming operations into the thread.

Thread

When an app starts, a thread is created for it, called the main thread. This thread is important because it handles scheduling events to the associated user interface widgets, including drawing events. Your app also interacts with components from the Android UI Toolkit (including components from Android.widget and Android.view packages) within this thread. Therefore, this main thread is sometimes referred to as the UI thread.

The system does not create a separate thread for each component. All the components in the same process are instantiated within the UI thread, and the system calls each component to be dispatched using this thread. Therefore, methods that respond to system calls (such as the OnKeyDown () method are used to capture user actions or a lifecycle callback function) are run in the UI thread of the process.

For example, when a user taps a button on the screen, your app's UI thread passes the click event to the widget, and the widget sets its push state, then sends a failed request to the event queue. The UI thread makes a queue operation on the request and then processes (notifies the widget to redraw itself).

This single-threaded model can have a bad effect when your app has a high response time to user interaction (unless you've implemented your app well). In particular, when everything in the app occurs within the UI thread, those long-time operations that access network data and database queries block the entire UI thread. When the entire thread is blocked, all events cannot be passed, including drawing events. It seems to the user that the application was suspended. Even worse, if the UI thread is blocked for a few seconds (currently 5 seconds), the system will pop up with the infamous "Application Not Responding" (ANR) dialog box. At this point the user may opt out of your app or even uninstall it.

In addition, the Android UI thread is not thread-safe. So you can't manipulate your ui-on a worker thread you have to manipulate your UI on the UI thread. Here are two simple rules about the Android single-threaded model:

    1. Do not block the UI thread
    2. Do not access the Android UI thread the non-UI line toolkit

Worker thread

Due to the above description of the single threading model, it is important to ensure a timely response to the application interface while the UI thread is not blocked. If you can't get the app to be played in a short time, then you should make sure to put these actions into a separate line thread ("background" or "worker" thread).

For example, the following code downloads an image in an extra thread and displays it in a imageview:

    1. New Thread (new Runnable () {
    2. public Void Run () {
    3. Bitmap B = loadimagefromnetwork ("http://example.com/image.png");
    4. Mimageview.setimagebitmap (b);
    5. }
    6. }). Start ();}

At first this code looks good because it creates a new thread to handle the network operation. However, it violates the second rule of the single threading model: thread access to the Android UI on non-UI lines toolkit-This example modifies ImageView on a worker thread. This can lead to unpredictable results and is difficult to debug.

To fix this problem, Android provides several ways to access Android UI Toolkit from non-UI threads. See below for this list:

    • Activity.runonuithread (Runnable)
    • View.post (Runnable)
    • View.postdelayed (Runnable, long)

Then, you can use the View.post (Runnable) method to modify the previous code:

  1. Public void OnClick (View v) {
  2. New Thread (new Runnable () {
  3. public Void Run () {
  4. final Bitmap Bitmap = loadimagefromnetwork ("http://example.com/image.png");
  5. Mimageview.post (new Runnable () {
  6. public Void Run () {
  7. Mimageview.setimagebitmap (bitmap);
  8. }
  9. });
  10. }
  11. }). Start ();}

Now this scenario is thread-safe: When this network operation is completed in a separate thread, the UI thread will operate on the ImageView.

However, as the complexity of operations grows, the code becomes more complex and more difficult to maintain. In order to handle more complex interactions with the worker thread, you might consider using handler in the worker thread to handle the messages in the UI thread. Perhaps the best solution is to inherit the Asynctask class, which simplifies the execution of the worker thread task that needs to interact with the UI.

Using Asynctask

Asynctask allows you to perform asynchronous operations on the UI. It does some blocking operations on a worker line thread and then gives the result to the UI main thread, which does not require you to process the thread or the handler.

Using it, you must inherit the Asynctask and implement the Doinbackground () callback method, which runs in a background thread pool. If you need to update the UI, you should implement OnPostExecute (), which takes the results out of Doinbackground () and runs inside the UI thread, so you can safely update your UI. You can run this task by invoking the Execute () method on the UI thread.

For example, you can use Asynctask to implement the previous example:

  1. Public void OnClick (View v) {
  2. new Downloadimagetask (). Execute ("http://example.com/image.png");
  3. }
  4. Private class Downloadimagetask extends asynctask<string,void,bitmap>{
  5. /** The system calls this to perform work in a worker thread and
  6. * delivers it the parameters given to Asynctask.execute () */
  7. protected Bitmap doinbackground (String ... urls) {
  8. return loadimagefromnetwork (urls[0]);
  9. }
  10. /** The system calls the perform work in the UI thread and delivers
  11. * The result from doinbackground () */
  12. protected void OnPostExecute (Bitmap result) {
  13. Mimageview.setimagebitmap (result);
  14. }}

The UI is now secure, and the code is simpler because asynctask separates what is being done in the worker thread from what is to be done in the UI thread.

You should read AsyncTask the reference documentation to better use it. Here's a quick overview of AsyncTask how it works:

    • You can specify the type of the parameter, the progress value, the end value of the task, the pattern used
    • doInBackground()method is automatically executed on the worker thread
    • onPreExecute(), onPostExecute() and onProgressUpdate() methods are all called in the UI thread
    • doInBackground()return value will be sent toonPostExecute()方法
    • You can call methods doInBackground() inside the method at any time publishProgress() to execute the method inside the UI thread onProgressUpdate()
    • You can cancel this task from any thread

Note: Another problem you may encounter when using a worker thread is that the runtime configuration change (such as the user changing the orientation of the screen) causes your activity to restart in an unpredictable way, This may kill your worker thread. In order to solve this problem you can refer to shelves this project.

Thread-Safe methods

In some cases, the method you implement may be called by multiple threads, so you must write it out of thread-safe.

RPM: Process and thread Summary for Android

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.