Android Threading Issues Handler & Synctask

Source: Internet
Author: User

In an Android application, many time-consuming tasks cannot be placed on the main thread, which is the UI thread, because it can cause a thread to clog and make the system judge that the program is running abnormally, so it requires multiple threads for asynchronous operations, and there are two ways to implement multithreading in Android, which is noted here As long as the UI update is involved, it must be done in the main thread

1.Handler

Handler has two important constructs, one is an empty parameter, one is with Looper, and the handler generated by the empty argument is associated with the current thread, usually the main thread, and the other can also provide a looper for it. This will bind to the thread on which the Looper is located. Handler provides the convenience for communication between different threads. To communicate with another thread, just get its handler. A handler can only be associated with one thread

The Handlerthread class is available in Android

The class itself is a thread class that supports message loops. Note Whether you want to start a thread or manually call Start ().

For a handlerthread, you can use Getlooper () to get its looper, but be aware that you must start the thread with start () before that, or looper is empty.

The biggest benefit of handler is that it not only sends messages, it can also send a runnable with post (). In this way, you can execute the code in the Runnable run () method within the specified process, that is, the cross-threading method call

For example:

public class Mainactivity extends activity{    private Handler Handler;    Private Handler Handlerthree;    Private Runnabletwo runnabletwo;     public void OnCreate (...)    {      Handlerthread thread = new Handlerthread ("Threadthree");      Thread.Start ();      Be sure to start () before getlooper       handlerthree = new  Handlerthree (Thread.getlooper ());       Handlerthree.post (Runnabletwo);    }     Handler    Handler = new Handler () {       replication Handlemessage method; ...     }      Runnabletwo runnabletwo =new Runnable () {       replication Run method, finally can be updated with the Handler.sendmessage (); method and the main thread communication for UI update}    Class Handlerthree extends handler{public    handlerthree (Looper Looper) {super (Looper);}}     }

2.AsyncTask

Android's Asynctask is more lightweight than handler and is suitable for simple asynchronous processing. The first thing to make clear is that Android has handler and Asynctask, both to not block the main thread (the UI thread), and that the UI update can only be done in the main thread, so asynchronous processing is unavoidable.

Android to reduce this development difficulty, provides the asynctask. Asynctask is a packaged background task class, as its name implies, an asynchronous task.

Asynctask directly inherits from the object class, where the position is android.os.AsyncTask. To work with Asynctask we are going to provide three generic parameters and overload several methods (at least one for overloading).

Asynctask defines three types of generic type params,progress and result.

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

Students who have used Asynctask know that an asynchronous load of data must be overridden by the following two methods:

    • Doinbackground (Params ...) is performed in the background, and more time-consuming operations can be placed here. Note that it is not possible to manipulate the UI directly. This method is performed on a background thread, and it usually takes a long time to complete the task's main work. You can call Publicprogress (Progress ...) during execution. To update the progress of the task.
    • OnPostExecute (Result) is equivalent to the way handler handles the UI, where it is possible to use the resulting processing action UI in Doinbackground. This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method

You also have to rewrite these three methods, if necessary, but not necessarily:

    • Onprogressupdate (Progress ...) You can use the progress bar to increase user experience. This method executes on the main thread and is used to show the progress of the task execution.
    • OnPreExecute () Here is the interface when the end user calls Excute, and the progress dialog can be displayed here before the task executes before calling this method.
    • Oncancelled () The action to be made when the user calls Cancel

Using the Asynctask class, here are a few guidelines to follow:

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

Three generic parameter descriptions for Asynctask (three parameters can be of any type)

First parameter: The parameter type of the incoming Doinbackground () method The second argument: the parameter type of the incoming Onprogressupdate () method The third argument: the parameter type of the incoming OnPostExecute () method, Also the type returned by the Doinbackground () method

One of the Asynctask implementation classes in the main thread, and then execute. Execute (params), where the params needs to be assigned when it is actually used, and this value is passed to the Doinbackground () method

For example, a task class that implements the inherited Asynctask

public class Task extends Asynctask<integer, Integer, string>{private TextView view;p rivate ProgressBar bar;public  Task (TextView View,progressbar bar) {super (); This.view = View;this.bar = bar;} /** * The integer parameter here corresponds to the first parameter in the Asynctask * Here the string return value corresponds to the third parameter of the Asynctask * The method does not run in the UI thread, primarily for asynchronous operations, all of which are not in the method Ability to set and modify space in the UI * but you can invoke the Publishprogress method to trigger Onprogressupdate to manipulate the UI */@Override protected String do          Inbackground (Integer ... params) {netoperator netoperator = new Netoperator ();          int i = 0;              for (i = ten; I <=; i+=10) {netoperator.operator ();          Publishprogress (i);      } return i + params[0].intvalue () + "";       }/** * Here the Intege parameter corresponds to the second parameter in the Asynctask * in the Doinbackground method, each call to the Publishprogress method will trigger Onprogressupdate execution * Onprogressupdate is executed in the UI thread, all can operate on UI space */@Override protected void onprogressupdate (Integer ... va lues) {int Vlaue = Values[0];      Bar.setprogress (Vlaue); }/** * Here the string parameter corresponds to the third parameter in Asynctask (that is, the return value of the receiving Doinbackground) * runs after the end of the Doinbackground method execution and runs in the UI thread to To set the UI space */@Override protected void OnPostExecute (String result) {View.settext ("End of asynchronous Operation execution" + R      Esult); }//The method runs in the UI thread and runs within the UI thread to set the UI space @Override protected void OnPreExecute () {View.settex      T ("Start executing asynchronous thread"); }  }

Multithreading is widely used in Android application development, it is very important!

Android Threading Issues Handler & Synctask

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.