Android SDK Process and Threads translation

Source: Internet
Author: User

When an application is just starting to run, and there are no other running components in the application, the Android system will open a new Linux process for the application in a separate running thread. By default, all components on an application run on the same process and thread (on a thread called "main"). If an application component starts running and there is also a process for the application (because of the other components that exist in the application), the component runs in this process and uses the thread that is executing. However, you can schedule different components in your application to run in a separate process, and you can also create additional threads for any process
This article discusses how processes and threads work on an Android program
Process
By default, all components on the same application run on the same process, and most applications should not change this default condition. Of course, you can also set up in the list, which process the component runs on.
This manifest file sets a list entry for each type of component-<activity>,<service>,<receiver>,<provider>-they all support Android: This property of process, which controls which component of a process is being run. You can set this property so that each component runs in its own process or some component shares a process. You can also set this property android:process, so that the components of different applications run on the same process-the implementation is provided to these applications with the same Linux user ID and given the same certificate.
The Android:process property is also supported in the <application> tag, which, after setting a value, applies this value to all components.
When there is not enough memory, and while other processes are requesting memory, Android shuts down a process for use by the user, and when a process is shut down, the application components running on the process will be destroyed. The process will run again until the components on the application run again.
For deciding which process to close, the Android system will measure which one is more important to the user. For example, compared to a window that is being visible, it may be easier to close an active window for a long period of inactivity, so deciding whether to terminate a process depends on the state of the component running in the process, and the rules that determine which process to close are discussed below
Cycle of the process
The Android system tries to keep the application process as far as possible, but it still needs to remove the old process to reclaim the memory for those new or more important processes. To determine which process holds or terminates, each process is zoned into a hierarchy of importance tables based on the process and state of the components running on them. The least important process is the first to be eliminated, then the second importance, and so on, to facilitate the recovery of system resources when necessary.
There are five levels in the hierarchy of importance table. The following list shows the importance of different types of processes (the first process is the most important and the last one is terminated).
1. Foreground process
Users to do something about a process that arises. Determine if a process is a foreground process and see if any of the following are true
2. Visible process
3. Service Process
4. Background process
The background process is also controlled by a list called the LRU (most recently Used list), and the longest time unused is first terminated
5. Empty process
Why does an empty process occur because the system pre-generates a process for a program so that it can load quickly

Thread

When an application is started, the system creates a thread execution for the application, called "main", which is important because it is responsible for distributing events to the appropriate user interface parts, including screen drawing events. It is also the thread in which your application interacts with the components that originate from the Android UI Toolkit (components from Android.widget and Android.view). Therefore, the main thread is sometimes referred to as the UI thread.
The system does not create a separate thread for each instance of the component. All components run in the same process and are instantiated in the UI thread, and each component of the system call is distributed through this thread. Typically, the method that responds to a system callback (for example: OnKeyDown) is also running in the UI thread of the process.

For example, when a user touches a button on the screen, the application's UI thread assigns the widget of the Touch event, which in turn sets the pressed state to pass an invalid request event queue. The UI thread dequeue request and notification widgets should change themselves.
When your application responds to user interaction to perform intensive work, this single-threaded model can produce poor performance unless you properly process your application. Specifically, if everything happens in the UI thread, performing long-term operations such as network access or database queries will block the entire UI. When a thread is blocked, all events cannot be distributed, including screen drawing events. From the user's point of view, the application hangs. Worse, if the UI thread is blocked for more than a few seconds now (about 5 seconds), the user interface pops up the "Application Not Responding" (ANR) dialog box. The user may decide to quit your application and uninstall it, usually with a dislike of emotion.

Additionally, the Andoid UI Toolkit is not thread-safe. Therefore, you cannot manipulate UI threads from a user interface that is allowed to operate from a worker. Therefore, there are two simple rules for Android's single-threaded model: 1, not blocking UI thread 2, not accessing the Android UI Toolkit from an external UI thread.
Worker threads
Because of the above-mentioned single-threaded model, it is critical that the application's UI is responsive so that you do not block the UI thread. If you have not performed in a timely manner, you should make sure that they are on separate threads ("background" or "work" threads)

For example, here are some code click listeners to download an image from a separate thread in ImageView and display
public void OnClick (View v) {
New Thread (New Runnable () {
public void Run () {
Bitmap B = loadimagefromnetwork ("Http://example.com/image.png");
Mimageview.setimagebitmap (b);
}
}). Start ();
}

First, the code seems to work well because it creates a new thread to handle the network operation. However, it violates the second rule of the single-threaded model: Do not access the Android UI Toolkit from outside-this example modifies the ImageView worker thread instead of the UI thread. This can lead to undefined and unexpected behavior, and it is difficult to take time to isolate the problem.
To fix this problem, Android provides several ways to access the UI thread from other threads. Here is a list of ways to get some help:
Activity.runonuithread (Runnable)
View.post (Runnable)
View.postdelayed (Runnable, long)
For example, you can modify the above code by using the View.post (Runnable) method
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 thread-safe: Network operations are manipulated from a separate thread after a period of time ImageView through the UI thread
However, with the complexity of operations, this code can become complex and difficult to maintain. To handle complex interactions with a worker thread, you might want to consider using a handler in your worker thread to process message delivery from the UI thread. Perhaps the best solution is to inherit the Asynctask class, which simplifies the execution of work-thread tasks and UI interactions.

Using Asynctask
Asynctask allows you to perform asynchronous work in your user interface. It performs a blocking operation on a worker thread and then publishes the results on the UI thread, without requiring you to handle the line Rountines accesses/or handlers yourself.
With it, you must implement the Asynctask subclass, implement the Doinbackground () callback method, run in a background thread pool. To update the UI, you should implement OnPostExecute (), Deliver results from Doinbackground (), and run in the UI thread, so you can safely update the UI. Then you can run the task from the UI thread by calling execute ().
For example, you can use Asynctask to implement the preceding example:
public void OnClick (View v) {
New Downloadimagetask (). Execute ("Http://example.com/image.png");
}

Private class Downloadimagetask extends Asynctask<string, Void, bitmap> {

Protected Bitmap doinbackground (String ... urls) {
Return Loadimagefromnetwork (Urls[0]);
}

protected void OnPostExecute (Bitmap result) {
Mimageview.setimagebitmap (result);
}
}
Now that the UI is secure, the code is simpler because it separates parts of the work that should be done on a worker thread should be on the UI thread.

Android SDK Process and Threads translation

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.