Easy to use threads in Android

Source: Internet
Author: User

When you start an Android program for the first time, a thread called "main" is created automatically. It is called the main thread or UI thread, it is very important because it is responsible for distributing events to the corresponding widgets, and also contains the events of the paint. The main thread runs through the entire process of interaction between the user and the Android widget. For example, when you touch a button on the screen, the UI thread Dispatch (Dispatch) Touch event sets Widget,widget to the pressed state and sends an invalid request to the event queue. The UI thread pops the request to the stack and notifies the widget to redraw itself.
The single-threaded model causes Android programs to be inefficient. Because each single thread executes long operations such as network requests, database queries, and drawing event (drawing events), the program's interface (UI) is blocked during this process. When a long task is being performed, no event is dispatched (dispatch), including the drawing event (drawing events). From the user's point of view, the change program has been terminated. Even worse, if the UI program is blocked for a few seconds (about 5s), the infamous ANR dialog box appears.
If you want to see how bad it is, you can write a simple program with a button that clicks on the event execution Thread.Sleep (2000) code. The button will remain in the pressed state for 2 seconds and then return to its normal state. This makes it easy for users to feel that the program is slow.

Now you know. Be sure to avoid long operations in the main thread, and you may use additional threads (background threads or worker threads) to perform operations. Let's take a look at the example of clicking the download image from the Web to ImageView:
public void OnClick (View v) {  new Thread (new Runnable () {public    void run () {      Bitmap B = loadimagefromnetwork ( );      Mimageview.setimagebitmap (b);    }  }). Start ();}
First, the code looks like a good solution to our problem because it does not block the UI thread, and unfortunately it violates the single threading model: the Android UI Toolbox (Toolkit) is not a thread-safe, and it is always placed on the main thread. This imageview is manipulated by a worker thread, which leads to a very magical problem. Tracking and repairing such a bug is difficult and time-consuming.
Android provides several ways to access the main thread from other threads. You may have used them a lot, but here is a complete list:
Activity.runonuithread (Runnable)
    • View.post (Runnable)
    • View.postdelayed (Runnable, long)
    • Handler
Any of these classes can fix our code:
public void OnClick (View v) {  new Thread (new Runnable () {public    void run () {      final Bitmap B = loadimagefromne Twork ();      Mimageview.post (New Runnable () {public        void run () {          mimageview.setimagebitmap (b);        }      );}  ). Start ();}
Unfortunately, these classes and methods cause our code to become complex and poorly readable. When you implement complex operations to update the interface frequently, it's much worse to use this approach. To solve this problem, Android1.5 provides a public class called Asynctask, which simplifies communication between the task thread and the main thread.
In Android1.0 and 1.1 can also be used asynctask only its name for Usertask.

The purpose of Asynctask is to help you manage threads. Our previous example can easily be rewritten as follows:
public void OnClick (View v) {  new Downloadimagetask (). Execute ("Http://example.com/image.png");} Private class Downloadimagetask extends Asynctask {     protected Bitmap doinbackground (String ... urls) {         return Loadimagefromnetwork (Urls[0]);     }     protected void OnPostExecute (Bitmap result) {         mimageview.setimagebitmap (result);}     }
Asynctask can be used by its subclasses. Remember that a asynctask instance must be created on the main thread and can only be executed once. Fully understand and use this class, you can read the Asynctask documentation. Here's a quick talk about how Asynctask works:
1> can specify its type by generic type: parameter, progress value, task result value. The 2>doinbackground () method automatically only wants to be able in the worker thread. 3>onpreexecute (), OnPostExecute (), Onprogressupdate () methods are all executed in the UI thread. The value returned by the 4>doinbackground () method is passed as a parameter to the OnPostExecute () method. 5> you can call the Publishprogress () method at any time in the Doinbackground () method to execute the Onprogressupdate () method in the UI thread.

In addition to the official documentation, you can read several complex examples of source code such as shelves(Shelvesactivity.java and Addbookactivity.java) and photostream( Loginactivity.java,photostreamactivity.java and Viewphotoactivity.java). I strongly recommend reading shelves 's source code to see how it saves the task (persist task) when it is configured to change (configuration changes), and how to cancel the task when the activity is destroyed.

Don't care if it uses asynctask, keep in mind the two principles of the single-threaded model (rule): Do not block the UI thread, and make sure that the Android UI Toolkit is accessible only in the UI thread (access). Asynctask makes it easier to do these things.

Easy to use threads in 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.