Android process and thread (2)

Source: Internet
Author: User

Thread

When an application starts, the android system will create an execution thread called "Main" for the application. This thread is very important because it is responsible for scheduling events for the appropriate user interface window, including plotting events. It is also the thread in which your application interacts with components in the android UI tool (these components are from Android. widget and Android. View packages ). For example, a "Main" thread is also called a UI thread.

The system does not create a separate thread for each component instance. All components running in the same process are instantiated in the UI thread, and the system calls each component scheduled by the thread. Therefore, methods that respond to the system callback (such as the onkeydown () method for reporting user actions or a lifecycle callback method) always run in the UI thread of the process.

For example, when you touch a button on the screen, the UI thread of your application schedules the touch event of the corresponding window and sets the button press status in sequence, and send a valid request to the event queue. The UI thread will send a request to the queue and notify the corresponding window to re-paint itself.

When your application needs to perform intensive work in response to user interaction, this single-threaded mode will reduce the execution efficiency unless you implement the application correctly. In particular, place everything that is happening in the UI thread. Long operations such as network access and database query will block the entire UI. When a thread is blocked, no event can be scheduled, including plotting events. From the user's perspective, the application seems to be suspended. Even worse, if the UI thread is blocked for several seconds (about five seconds), the user will see the notorious "application has no response" (ANR) dialog box. Then the user may decide to exit your application, and if they do not feel good, they will uninstall the application.

In addition, the android UI tool set is not thread-safe. Therefore, you cannot control your UI by a working thread-you must use the UI thread to control your UI. In this way, there are two simple rules for the android single-thread mode:

1. Do not block the UI thread;

2. do not access the android UI toolkit from outside the UI thread.

Worker thread

Because of the single-thread mode described above, it is vital that your application UI response does not block the UI thread. If you are not performing instantaneous operations, you should use a separate thread (background or working thread) to work.

For example, the click listener code downloads an image from a separate thread and displays it in an imageview object:

Public void onclick (view v ){
New thread (New runnable (){
Public void run (){
Bitmap B = loadimagefromnetwork ("http://example.com/image.png ");
Mimageview. setimagebitmap (B );
}
}). Start ();
}

Looking at the above Code, it seems to work well because it creates a new thread for processing network operations. However, it violates the second rule of Single-threaded mode: do not access the android UI toolset from external UI threads-this example modifies the imageview object in the working thread rather than in the UI thread. This will lead to unknown and uncertain abnormal behavior, which is difficult and time-consuming to find the problem.

To solve this problem, Android provides the following methods to access the UI thread from other threads:

1. activity. runonuithread (runnable)

2. View. Post (runnable)

3. View. postdelayed (runnable, long)

For example, you can use the view. Post (runnable) method to modify the above 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 ();
}

The current implementation is thread-safe, because network operations are completed in a separate thread, while imageview object operations are completed in the UI thread.

However, the complexity of operations increases. This type of code makes code maintenance complicated and difficult. To handle more complex interactions with working threads, you may consider using handler objects in your work thread to handle messages sent by the UI thread. Inheriting the asynctask class may be the best solution, which simplifies the job thread to execute tasks that need to interact with the UI.

Use ansynctask class

The asynctask class allows you to perform asynchronous work on the user interface. It executes a blocking operation in the working thread and then publishes the execution result on the UI thread. You are not required to handle the thread and/or processor on your own.

To use this class, you must inherit the asynctask class and implement the doinbackground () callback method, which runs in the background thread pool. To update the UI, you should implement the onpostexecute () method, which provides results from the doinbackground () method and runs in the UI thread, so you can safely update your UI. Then you can run the task from the UI thread through the execute () method.

For example, you can use the asynctask class method to implement the previous example:

Public void onclick (view v ){
New downloadimagetask(cmd.exe cute ("http://example.com/image.png ");
}

Private class downloadimagetask extends asynctask <string, void, bitmap> {
/** The system callthis to perform work in a worker thread and
* Delivers it the parameters given to asynctask.exe cute ()*/
Protected bitmap doinbackground (string... URLs ){
Return loadimagefromnetwork (URLs [0]);
}

/** The system callthis to perform work in the UI thread and delivers
* The result from doinbackground ()*/
Protected void onpostexecute (Bitmap result ){
Mimageview. setimagebitmap (result );
}
}

The current UI is secure and the code is simplified, because it divides the work into the part executed in the work thread and the part executed in the UI thread.

To fully understand this class, you should read the asynctask reference, but you can quickly view the working method of this class as follows:

1. You can specify parameters of common types, such as the progress value and the end value of the task;

2. The doinbackground () method is automatically executed on the worker thread;

3. The onpreexecute (), onpostexecute (), and onprogressupdate () methods are all called on the UI thread;

4. the return value of the doinbackground () method is sent to the onpostexecute () method.

5. You can call the publishprogress () method in the doinbackground () method at any time to execute the onprogressupdate () method on the UI thread;

6. You can cancel tasks from any thread at any time.

Warning:When you use the activity of a working thread to cause abnormal restart due to configuration changes during the runtime (for example, when the user changes the screen direction), you may encounter another problem: may destroy your worker threads. For more information about how to keep your background tasks and how to cancel tasks correctly when the activity is destroyed, see the source code of the shelves sample application. Http://code.google.com/p/shelves)

Thread Security Method

In some cases, the method you implement may be called by multiple threads. Therefore, you must write a thread-safe method.

Thread security is mainly for methods that can be remotely called, such as methods in the binding type service. When a method call in the ibinder implementation class comes from the process that runs with the ibinder object, this method will be executed in the caller's thread. However, when the call comes from another process, the thread in which the method is executed (not executed in the UI thread of the process) is selected from the thread pool of the process that the system maintains with the same ibinder object ). For example, the onbind () method of a service will be called by the main thread of the service process, and the methods implemented in the objects returned by the onbind () method (such as a subclass that implements the RPC method) will be called from the thread pool. Because a service can have multiple clients and multiple threads can call the same ibinder object method at the same time, the ibinder method must implement thread security.

Similarly, a content provider can accept data requests from other processes. Although the contentresolver and contentprovider classes hide how to manage inter-process communication details, the contentprovider methods (query (), insert (), delete (), update () that respond to those requests () and GetType () are called from the thread pool in the content provider process, rather than the UI thread of the process. Because these methods may be called by multiple threads at the same time, they must also implement thread security.

Inter-process communication

Android uses Remote Procedure Call (rpcs) to provide a mechanism for inter-process communication (IPC), in which a method is called by activity or other application components, it is not executed locally, but remotely (other processes). It returns a result to the caller. This requires that a method be decomposed into calls and data that can be understood at the operating system level, and passed to the remote process and its address space from the local process and address space, then re-assemble and execute the code at the place where the call is made. Then, the returned values are reversed. Android provides all the code for executing the IPC transmission, so you can focus on the definition and implementation of the RPC programming interface.

To run IPC, your application must bind a sevice using the bindservice () method.

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.