Android process and thread detail

Source: Internet
Author: User

And the thread of the application already exists (because another component of the application is already running), the component will start in the existing process and run on the same thread. However, you can simply schedule different components to run in different processes, and you can create additional threads for any program.

Process

By default, all components of the same program are running in the same process and most programs do not have to change this situation. However, if you want to be different, you can also implement it by modifying the manifest file.

All those items in the manifest file that support the android:process attribute (<activity>,<service>, <receiver>, and <provider> Can specify a process, and the components will run in the process. You can set this property so that each component runs on its own process or just some of the components share a process. You can also set up android:process so that components of different applications can run on the same process-if they share the same user ID and have the same digital certificate.

The <application> element also supports the Android:process property, which is used to specify a default value for all components.

Android may decide to close a process at some point, such as less memory and a more pressing need for another process to start. When the process is closed, the components are destroyed. If these components are needed again, the process will be created again.

When deciding which threads to shut down, the Android system measures how tightly the processes are to the user. For example, processes that contain all of the activity that are not visible are more likely to be closed than a process with visible activity. How to decide whether a process is closed depends on the state of the components that are running in the process. The rules for deciding to close the process are discussed below.

Lifetime of the process

The Android system will try to maintain the life of a process until it finally frees up memory space for new, more important processes. To decide which one to kill and which to stay, the system places the process at a different level of importance according to the state of the components and components running in the process. When system resources are needed, the lower the importance level is eliminated first.

The importance level is divided into 5 files. The importance levels of different types of processes are listed below (the first process type is the most important and is the last to be killed):

1 foreground process

This process is required for what the user is currently doing. A process is considered a foreground process if the following conditions are met:

This process has an activity that is interacting with the user (the Onresume () method of the activity is invoked).

This process has a service that is bound to an activity that is interacting with the user.

This process has a foreground-run Service-service called Method Startforeground ().

This process has a service that is executing any of its life cycle callback methods (OnCreate (), OnStart (), or OnDestroy ()).

This process has a broadcastreceiver that is executing its onreceive () method.


Usually, at any point in time, only a few foreground processes exist. They can only be killed when they reach a conflict that cannot be adjusted--if the memory is too small to continue running. Typically, at this point, the device reaches a paging state of memory, so you need to kill some foreground process to ensure that the user interface reacts

2 Visible processes

A process does not have a component running at the foreground, but it can still affect what the user sees. The process is visible when the following conditions are true:

This process has an activity that is not in the foreground but is still visible (its OnPause () method is invoked). This is the case when a foreground activity starts a dialog box.

3 Service Process

A visible process is considered to be extremely important. And, unless you kill it to ensure that all foreground processes are running, you cannot move it.

This process has a service that is bound to visible activity.

A process is not within the above two types, but it runs a service that is started by StartService ().

Although a service process does not directly affect what users see, they usually do something that users care about (such as playing music or downloading data), so the system does not kill the foreground process and the visible process if it does not survive. 4 Background process

A process has an activity that is not currently visible (the OnStop () method of the activity is invoked).

Such processes do not directly affect the user experience, so the system can kill them at any time to provide storage space for the foreground, visible, and service processes. There are usually a lot of background processes running. They are kept in a LRU (recently least used) list to ensure that the process of owning the activity that was recently seen was eventually killed. If an activity implements its lifecycle method correctly and preserves its current state, the process that kills it will not affect the user's visual experience. Because when the user returns to the activity, the activity restores all its visible state.

5 Empty processes

A process does not own the active component into.

The only reason to keep such a process is caching, which increases the speed at which the next component will start when it is running. Systems often kill them to balance the overall system resources between the process cache and the underlying kernel cache.


In line with the importance of the components currently active in the process, Android puts the process at its highest possible level. For example, if a process has a service and a visible activity, the process is defined as a visible process, not a service process.

In addition, the level of a process may be increased if it is relied upon by other processes-a process that serves other processes with a level that cannot be lower than the service process.

Because the process of owning a service is higher than a process with a background activitie, it is best to start a service rather than simply create a worker thread when an activity initiates a long-running operation. Especially if this operation may be longer than the life of the activity. For example, an activity that uploads images to a Web site should start a service so that uploads can continue to be performed in the background while the user is away. Using a service ensures that the operation is at least at the "service process" level, without having to worry about whether or not the activity has been unfortunate. This is also the reason that the broadcast receiver should use the service rather than simply using a thread.

The code is as follows Copy Code

Url:http://www.111cn.net/help/zt/21705.html


Android process and thread detail two: threads
Thread


When an application is started, the system creates an execution thread called "main". This thread is important because it is responsible for distributing events to user interface controls. which contains drawing events. It is also where your application interacts with the Interface Toolkit (Android.widget and components in the Android.view package). The main thread is also called an interface thread.


The system does not create threads for each instance of the component separately. All components running in a process are instantiated in the interface thread, and the system calls to each component are distributed in this thread. As a result, methods that respond to system calls (such as onkeydown () or a lifecycle callback method that reports user actions) are always processes in the interface thread.


For example, when a user touches a button on the screen, the interface thread of your application sends the touch event to the control, then the control sets its pressed state and sends a request to the event queue that its own interface becomes invalid, and the interface thread pulls the request out of the queue and notifies the control to redraw itself.


When your application performs a large number of operations in response to user interaction, this single-threaded pattern can lead to low performance unless you can optimize your program correctly. In particular, if everything happens in the interface thread, performing time-consuming operations such as network connections or database requests will prevent the entire interface from responding. When a thread is blocked, events cannot be distributed, including drawing events. From the user's point of view, the program response is too slow. Even worse, if the interface thread is blocked for a few seconds (big 5 seconds), the user complains that the program is unresponsive and the user may opt out and delete your application.


In addition, the Andoid interface is not thread-safe. So you can never manipulate your interface in a working thread-you can only manage your interface in an interface thread. So, there are two simple rules for single-threaded patterns:

1 do not block interface thread

2 do not operate the interface outside the interface thread.


Worker threads

Because of the single-threaded pattern above, it is important not to block your interface threads so that your application's interface remains responsive, so if you have tasks that you can't do quickly, you should put them on another thread (background or worker threads).

For example, the following code is in response to the Click event, downloading a picture in another thread and displaying it in a imageview:

The code is as follows Copy Code
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 looks like a good job because it creates a new thread for network operations. However, it violates the second rule: do not manipulate the interface outside of the interface thread-it simply modifies the imageview in the worker thread. This leads to undefined exceptions, and it is difficult to debug tracing.


To correct this problem, Android offers a number of ways to manipulate the interface from other threads. The following are the available methods:

The code is as follows Copy Code

1 Activity.runonuithread (Runnable)

2 View.post (Runnable)

3 view.postdelayed (Runnable,long)


For example, you can use View.post (Runnable) to fix the above problem:

The code is as follows Copy 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 ();
}

Now this implementation is finally thread-safe: The network operation is in another thread and the ImageView is changing in the interface thread.

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.