An example analysis of Asynctask and handler usage in Android _android

Source: Internet
Author: User

This article illustrates the use of Asynctask and handler in Android. Share to everyone for your reference, specific as follows:

First, we need to be clear about the next concept, what is the UI thread. As the name suggests, the UI thread is the thread that manages the user interface!

The Android UI thread operation is not safe, and operations that interact directly with the user must be done in the UI thread. This pattern is called single-threaded mode.

In single-threaded mode, we must be careful: do not block UI threads, make sure that UI components are accessed only in the UI thread

When we are going to perform a complex and time-consuming algorithm and ultimately to reflect the results of the calculation to the UI, we will find that we have no way to ensure that the above two requirements, we will certainly think of opening a new thread, so that this complex and time-consuming task to the background to execute, but the execution is completed? We found that we could no longer interact with the UI.
To solve this situation, Android offers us a lot of options.

1, handler and message mechanism: through the display of the throw, capture messages and the UI to interact;

2), Activity.runonuithread (Runnable): Executes immediately if the current thread is a UI thread, otherwise, the thread action in the parameter is placed in the event queue of the UI thread, pending execution.

3), View.post (Runnable): Put the operation into the message queue, if put successfully, the operation will execute in the UI thread and return True, otherwise return false

4), view.postdelayed (Runnable, long) is basically the same as the third, except that a delay time is added.

5), android1.5 later provides us with a tool class to fix this problem asynctask.

Asynctask is an abstract class that defines three generic type Params,progress,result.

Params an input parameter that initiates a task execution, such as the URL of an HTTP request
Progress the percentage of background task execution.
Result background The results of the final return of the task, such as String

Using a program call, what the developer needs to do is implement these methods.

1) Sub-class of Asynctask
2 Implement the following one or several methods defined in Asynctask

OnPreExecute (), which is invoked by the UI thread before performing the actual background operation. You can do some preparation work in this method, such as displaying a progress bar on the interface.
Doinbackground (Params ...)is executed immediately after the OnPreExecute method is executed, which runs in a background thread. This will be the main responsibility for performing the time-consuming background computing work. You can call the Publishprogress method to update the real-time task progress. This method is an abstract method that must be implemented by subclasses.
onprogressupdate (Progress ...), after the Publishprogress method is invoked, UI thread calls this method to show the progress of the task in the interface, for example, through a progress bar.
OnPostExecute (Result), after Doinbackground execution completes, the OnPostExecute method is invoked by the UI thread, and the results of the background calculation are passed to UI thread through this method.

For the correct use of the Asynctask class, here are a few guidelines to follow:

1 The instance of the task must be created in UI thread
2 The Execute method must be called in UI thread
3 Do not manually invoke OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods
4 The task can only be executed once, otherwise the exception will occur when multiple calls are made

Package Cn.com.chenzheng_java; 
Import Android.os.AsyncTask; /** * * @author Chenzheng_java * @description Asynchronous Task Acynctask Example * */public class Myasynctask extends Asynctask 
 <string, Integer, object> {/** * This method is invoked by the UI thread, where users can enjoy the UI components. 
 * Most of the time, we will display a progress bar here to show that the background is performing a function. 
 * * @Override protected void OnPreExecute () {super.onpreexecute (); 
 /** * This method is invoked by the background process to perform the main time-consuming computations. * This method is invoked after the OnPreExecute method. Of course, in the process of implementation * We can call the Publishprogress method every few seconds, update * Progress information/@Override protected Object doinbackground (String ... para 
 MS) {return null; After the publishprogress is invoked in/** * doinbackground, the UI thread invokes the method. 
 Here you can dynamically change the progress bar and let the user know the current progress. 
 * * @Override protected void onprogressupdate (Integer ... values) {super.onprogressupdate (values); /** * is invoked by the UI thread after Doinbackground execution. 
 You can return the final result of our calculations to the user here. 
 * * @Override protected void OnPostExecute (Object result) {Super.onpostexecute (result);

 } 
}

The following are the most essential Multithreading: Hanlder and message mechanisms:

Why multiple threads are required:

In the day-to-day application, we usually need to deal with some "backstage, the user is not visible" operation, for example, we need to download a music, if your application must wait for users to download the completion of other operations, it must make users very uncomfortable. At this point, our usual practice is to let these operations to the background, and then after the completion of the background, and then to the user pop-up corresponding message. At this point, we need to use multithreaded mechanisms and then do this by creating a new thread.

Understand, to achieve the requirements, we are ready to proceed to achieve. But, after further understanding, we are tragically discovering that the threading mechanism in Android is that you can only interact with the user in the UI thread. When we created a new thread, performed some background operations, and after the execution, we wanted to give the user a pop-up dialog to confirm, but it was a tragic discovery that we could not return to the main thread of the UI at all. (UI threads are the threads that you currently see that interact with these interfaces).

At this point, if we want to implement these functions, we need a handler and message mechanism that Android provides for us.

First explain the programming mechanism:

we typically create a handler,handler in the UI thread equivalent to a processor, which is primarily responsible for processing and binding to the message in the handler thread. Each handler must be associated with a looper, and the two are one by one corresponding, note that this is very important oh! In addition, Looper is responsible for taking out a message from its internal MessageQueue to the handler for processing. Since our handler here is implemented in the UI thread, after such a handler and message mechanism, we can go back to the UI thread.

handler: The worker who handles the returned data from the background process.
Message: The data returned by the background process, which can store data formats such as bundle
MessageQueue: is part of the thread-corresponding looper, which is responsible for storing the message that is thrown back from the background process and the current handler binding, is a queue.
looper: Looper is the equivalent of a MessageQueue manager, it will continue to loop through the queue, and then will meet the conditions of the message one by one to handler to deal with.

Note that handler is declared in the UI thread, and if we execute a thread directly with similar code, we actually do not create a new thread because handler is already bound to the Looper in the default UI thread.

If you are interested, you can look at the default null constructor for handler to know why, which directly binds the current UI thread's Looper.

A simpler and more practical example is given below.

public class Mainactivity extends activity implements Onclicklistener {private Button btntxt; 
  Private TextView Tvtxt; 
  Private StringBuffer returnmsg; 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.activity_main); 
    Btntxt = (Button) Findviewbyid (r.id.btntxt); 
    Tvtxt = (TextView) Findviewbyid (r.id.tvtxt);     
  Btntxt.setonclicklistener (this); 
    @Override public void OnClick (View v) {returnmsg = new StringBuffer (); 
    Creates a thread that contains looper, where if there is no handlerthread call, the myrunnable will be placed directly behind the UI thread Queue (Myhandler.post (new myrunnable ()) 
    Handlerthread handlerthread = new Handlerthread ("Handler_thread");   Handlerthread.start ();    Start custom processing thread MyHandler = new MyHandler (Handlerthread.getlooper ());    Binds the handler to the new thread myhandler.post (the newer myrunnable ()); Execute task in new thread}/** main thread Handler, can interact with UI controls/Handler Mainhanlder = new Handler () {@Override PublIC void Handlemessage (Message msg) {if (Msg.what = = 0) {Tvtxt.settext (returnmsg.tostring ()); 
  Dealing with the mainline program control (direct Access)}}; 
  /** constructs Hanlder, cannot interact directly with UI controls/private MyHandler MyHandler = null; 
     Private class MyHandler extends handler{/** * Using the default constructor, Handler binds the looper of the current UI thread. 
     * If you want to use multithreading, you cannot use the default construction method here. 
    * * Public MyHandler () {super (); 
    }/** Constructor, custom Looper */public MyHandler (Looper looper) {super (Looper);    
      }//handling specific message messages, inheriting from the parent class method @Override public void Handlemessage (msg) {int what = Msg.what;      Bundle Bundle = (Bundle) msg.obj; 
      Extracts information in bundle String name = bundle.getstring ("name"); 
      String sex = bundle.getstring ("Sex"); 
      Boolean marry = Bundle.getboolean ("Marray"); 
      int age = Bundle.getint (' age ');    StringBuffer strbuf = new StringBuffer (); Stitching bundle Information Strbuf.append ("what ="). Append (What). Append ("\ n");
      Strbuf.append ("name ="). Append (name). Append ("\ n"); 
      Strbuf.append ("sex ="). Append (Sex). Append ("\ n"); 
      Strbuf.append ("Marry ="). Append (Marry). Append ("\ n"); 
      Strbuf.append (' age = '). Append (age). Append ("\ n \ nthe"); 
      Strbuf.append ("http://blog.csdn.net/sunboy_2050");  Returnmsg = Returnmsg.append (STRBUF);    Save the results to be displayed mainhanlder.sendemptymessage (0); 
    Sends a message to the main thread mainhanlder, interacting with the UI control to display the result super.handlemessage (msg); }//Constructs Runnable, handles background business logic, such as downloading private class Myrunnable implements runnable{@Override public void Run (  {try {message msg = Message.obtain (MyHandler); 
        Capture MyHandler Message Msg.what = 10;        Bundle Bundle = new Bundle (); 
        Encapsulation Bundle Information bundle.putstring ("name", "Yanggang"); 
        Bundle.putstring ("Sex", "pure Boy"); 
        Bundle.putboolean ("Marry", false); 
        Bundle.putint ("Age", 18); 
        Msg.obj = bundle; Long Thid = Thread.CurrentThread (). GetId (); 
        Returnmsg.append (Thid). Append (": Send msg start ..."). Append ("\ n");   Msg.sendtotarget (); 
      Send Message to MyHandler Thread.Sleep (3000); 
        catch (Exception e) {log.i ("", "Runnable send msg error ..."); 
      E.printstacktrace (); } 
    } 
  } 
}

Run Result:

Full instance code code click here to download the site.

I hope this article will help you with the Android program.

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.