Simple usage of asynctask in Android "Go"

Source: Internet
Author: User

When developing an Android mobile client, you tend to use multithreading to do it, and we typically put time-consuming operations on separate threads to avoid taking the main thread and creating a bad user experience for the user. However, the main thread (UI thread) cannot be manipulated in a child thread, and an error occurs when manipulating the UI thread in a child thread. So Android provides a class handler to update the UI thread in a child thread, updating the UI interface with a message-sending mechanism and presenting it to the user. This solves the problem of the child thread updating the UI. However, time-consuming task operations always start some anonymous sub-threads, and too many sub-threads bring a huge burden on the system, resulting in some performance problems. So Android provides a tool class Asynctask, which, as the name implies, executes tasks asynchronously. This asynctask is born to handle some of the more time-consuming tasks behind the scenes, to give users a good user experience, from the programming syntax is much more elegant, no longer need child threads and handler to complete the asynchronous operation and refresh the user interface.

First of all, about the Android.os.AsyncTask class:

* The Android Class Asynctask wraps the inter-thread communication, providing a simple programmatic way to communicate with the background thread and the UI thread: The background thread executes the asynchronous task and notifies the UI thread of the result of the operation.

* Asynctask is an abstract class. Asynctask defines three generic type params,progress and result.
* Params starts the input parameters of the task execution, such as the URL of the HTTP request.
* Percentage of Progress background task execution.
* Result background performs the final return of the task, such as String,integer.

* The implementation of Asynctask is divided into four steps, each of which corresponds to a callback method that the developer needs to implement.

* 1) Inherit Asynctask
* 2) Implement one or more of the following methods defined in Asynctask
* OnPreExecute (), this method will be called by the UI thread before performing the actual background operation. You can do some preparatory work in the method, such as displaying a progress bar on the interface, or instantiating some controls, and this method can be used without implementation.
* Doinbackground (Params ...), which executes immediately after the OnPreExecute method executes, runs in a background thread. This will be the main responsibility for performing those very time-consuming background processing work. You can call the Publishprogress method to update the real-time task progress. The method is an abstract method that the subclass must implement.
* Onprogressupdate (Progress ...), after the Publishprogress method is called, the UI thread will invoke this method to show the progress of the task on the interface, for example, by showing it through a progress bar.
* OnPostExecute (Result), after Doinbackground execution completes, the OnPostExecute method is called by the UI thread, and the results of the background are passed to the UI thread through the method and presented to the user on the interface.

* oncancelled (), called when the user cancels the thread operation. Called when oncancelled () is called in the main thread.

To properly use the Asynctask class, here are a few guidelines to follow:

1) The instance of the task must be created in the UI thread

2) The Execute method must be called in the UI thread

3) do not manually call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These methods need to be instantiated in the UI thread to invoke this task.

4) The task can only be executed once, otherwise an exception will occur when multiple calls are made

The parameters of the Doinbackground method and OnPostExecute must correspond, both of which are specified in the generic parameter list of the Asynctask declaration, the first is the Doinbackground accepted parameter, the second is the parameter that shows the progress, The third one is the Doinbackground return and the OnPostExecute passed in parameters.

Below is a demo to illustrate how to use the Android.os.AsyncTask class, show progress through the progress bar, and then use TextView to display the progress value. The program structure diagram is as follows:



[1] \layout\main.xml layout File source code is as follows:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:orientation=" vertical "    android:layout_width=" fill_parent "    android:layout_height= "Fill_parent"     >    <textview          Android:layout_width= "Fill_parent"         android:layout_height= "Wrap_content"          android:text= "Hello, Welcome to Andy ' s blog!" />    <Button       android:id= "@+id/download"        android: Layout_width= "Fill_parent"        android:layout_height= "wrap_content"         android:text= "Download"/>    <textview         android:id= "@+id/tv"        android:layout_width= "fill_parent"         android:layout_height= "Wrap_ Content " &nbSp      android:text= "Current progress display"/>    <ProgressBar       android:id= "@+ ID/PB "       android:layout_width=" fill_parent "       android:layout_height= "Wrap_content"        style= "? Android:attr/progressbarstylehorizontal"/></linearlayout >

[2] The Mainactivity.java source code in/SRC is as follows:
Package Com.andyidea.demo; import Android.app.activity;import Android.os.asynctask;import android.os.Bundle; Import Android.view.view;import Android.widget.button;import Android.widget.progressbar;import Android.widget.textview; public class Mainactivity extends Activity { button download; ProgressBar PB; TextView tv;    /** Called when the activity is first created. */    @Override     public void onCreate (Bundle savedinstancestate) {        Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.main);        pb= (ProgressBar) Findviewbyid (R.ID.PB);        tv= (TextView) Findviewbyid (r.id.tv);                download = (Button) Findviewbyid (r.id.download);        Download.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {Downloadtask Dtask = new DownloadtAsk ();d task.execute (100);}});    }        class Downloadtask extends Asynctask<integer, Integer, string>{& nbsp   //after the angle brackets are parameters (in the example is thread break time), progress (publishprogress used), return value type         @ overrideprotected void OnPreExecute () {    //The first method of execution Super.onpreexecute ();}      @Overrideprotected String doinbackground (Integer ... params) {//Second execution method, OnPreExecute () executes after execution for ( int i=0;i<=100;i++) {pb.setprogress (i);p ublishprogress (i); try {thread.sleep (params[0]);} catch ( Interruptedexception e) {e.printstacktrace ();}} Return "execution complete";}   @Overrideprotected void Onprogressupdate (Integer ... progress) {//This function is triggered when Doinbackground calls Publishprogress. Although the call is only one parameter//But here is an array, so you want to use progesss[0] to take the value//nth parameter Progress[n] to take the value tv.settext (progress[0]+ "%"); Super.onprogressupdate (progress);}   @Overrideprotected void OnPostExecute (String result) {//doinbackground when returned, in other words, doinbackground triggered after execution// The result here is the above DoinbackgroundThe return value after the line, so here is "execution complete" settitle (result); Super.onpostexecute (result);        }}

[3] below to see the operation results of the program
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.