Go Android: Application of asynchronous Processing Asynctask (II.)

Source: Internet
Author: User

2014-11-07
Since the UI old people are so busy, we developers must not play gooseberry to the trouble of blocking the UI thread or something, otherwise the UI interface should stop responding-this is not the rhythm of the scold?! So we know that with the Handler+thread method, the time-consuming task is handled in the sub-thread, and the UI is updated via the handler notification UI after the task is completed.   However, there are some people who think that using handler+thread code will be more cumbersome, of course, some of these people include our great Google. So Asynctask (asynchronous task) turned out in Android 1.5; Compared to handler, because of the relatively good package, the Asynctask appears more lightweight, suitable for simple asynchronous processing, of course, the use of the relatively concise, sure enough is Google's pro-son!   Overview   Asynctask is an abstract class, usually an inherited life. The internal of the asynctask will maintain a static thread pool, each background task will naturally be committed to the thread pool to run, but also use the handler+thread mechanism to invoke Asynctask's various callback methods, the callback method is run in the main thread, so we all know what to do (~ o ~) ~zz (hurry up with the UI interface set near it).   We know Asynctask<params, Progress, Result> is an abstract class, and we can see here that it supports three generics:  1, Params: When our asynctask starts to work, We give him the type of the input parameter, that is, the parameter passed to the background  2, Progress:asynctask to us to report the parameter type of its work progress, for example is the percentage of download Progress  3, Result: Background execution task is completed, The parameter type of the returned result   if a generic type we do not need to specify, we can openly specify void, nothing asynctask will not be sad drop.   Of course Google also help us to the Asynctask background task to run five states, namely: 1, ready to run, 2, is running in the background, 3, progress updates, 4, complete background tasks, 5, cancel the task. Each state has a corresponding callback method in the Asynctask.  1, ready to run: OnPreExecute (), the callback method is called immediately in the UI thread when the task is turned on, and is called before the background time-consuming operation is performed, usually to do some initialization work, such as displaying a progress bar on the interface.  2, running in the background: Doinbackground(Params ...), this callback function is called by the background thread immediately after the execution of the OnPreExecute () method, which is the time-consuming task that the background thread is going to complete, and because it is called by a background thread, we cannot update the UI interface directly here. Should use Publishprogress (Progress ...) Trigger callback method Onprogressupdate (Progress ...) The result of the task calculation must be returned by the function and passed to OnPostExecute ().  3, Progress Update: Onprogressupdate (Progress ...), calling the Publishprogress () method in Doinbackground () to update the execution progress of the task will trigger the method in the main thread. Typically used to dynamically display a progress bar. &NBSP;4, complete background task: OnPostExecute (Result), when Doinbackground () completes, the system automatically calls the OnPostExecute () method and Doinbackground () is passed to the method by the return value of the  5, cancels the task: oncancelled (), called when the Cancel () method of the Asynctask is called.   Case   Reference code:  copy code public class Mainactivity extends actionbaractivity implements onclicklistener{      Private Button startdownload;    private ProgressBar probar;    private TextView Tv;&nbs P       Private Downtask task;        @Override     protected void on Create (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (R. Layout.activity_main);                startdownload = (Button) Findviewbyid (r.id.startdownload);        Probar = (ProgressBar) Findviewbyid (R.id.probar);  & nbsp     TV = (TextView) Findviewbyid (r.id.tv);                Startdown Load.setonclicklistener (this);           }     @Override     public void OnClick (View v) {        task = new Downtask ();//The same asynctask execute can only be called once task.execute ("input parameter can be null");//Call to execute will callback OnPreExecute method   }        class Downtask extends Asynctask<string, Integer, string>{ & nbsp       @Override//This method is not run on the main thread, can take time to operate, cannot update UI interface, other methods run for main thread         protected String Doinbackground (String ... params) {//params parameters for execute input             for (int i = 1; I <= 10 0; i++) {                try {//Analog download action                     Thread.Sleep (333);                    PUBLISHPROGR ESS (i);//pass parameter I and trigger Onprogressupdate callback method                } catch ( Interruptedexception e) {                    E.printstacktrace ();               }           }        & nbsp   String result = "task completed";  &nbsp         return result;//will call OnPostExecute and pass result to the callback method        }   & nbsp     @Override         protected void OnPreExecute () {//The callback method will be called when it finishes executing doinbackground            Probar.setmax (+);            probar.setprogress (0) &NB Sp           tv.settext ("Start download");       }         @Over ride        protected void OnPostExecute (String result) {//doinbackground After the end of the callback method.             Toast.maketext (mainactivity.this, result, Toast.length_short). Show ();  & nbsp         tv.settext ("Download Complete");       }         @Override &NB Sp       protected void onprogressupdate (Integer ... values) {//Notification UI interface update           &NBS P Probar.setprogress (VALues[0]);       }           }  Copy code layout file:  copy code < LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"     xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation=" vertical ">        <Button        android:id= "@+id/startdownload"         android:layout_width= "Wrap_content"         android:layout_height= "wrap_content"         android:text= "Start Download"/>& nbsp   <ProgressBar         android:id= "@+id/probar"         Android: Layout_width= "Match_parent"         android:layout_height= "wrap_content"         style= "@android: Style/widget.progressbar.horizontal"        />    <TextView         android:id= "@+id/tv"         Android: Layout_width= "Wrap_content"         android:layout_height= "wrap_content"         android:textcolor= "#000000"         android:textsize= "20SP"        />& Nbsp;</linearlayout> Copy Code Explanation:  1, click button to instantiate a Asynctask inheriting subclass, a task will be created at this time. Next, the Execute execute (params) method starts the asynchronous task. (an instance of the same asynctask can execute only once, and multiple executions will throw an error).  2, after execute () is executed, the OnPreExecute () callback method is triggered to set the initial properties of the progress bar. After OnPreExecute () is executed, the Doinbackground (params) will be executed in the background thread, which receives the execute incoming parameters and takes time to operate, here is the simulation network file download task.  3, Doinbackground () in a background thread run, if you need to interact with the UI master to update progress, you can call the Publishprogress (values) method, which will trigger the onprogressupdate that is running on the UI main thread. (values) callback method, where the progress bar is updated in the code.  4, when the background task executes, calls OnPostExecute (Result), and the passed in parameter is the object returned in Doinbackground ().   Note  1, do not execute execute () multiple times in the same Asynctask instance, the correct method is to execute execute () once for the new asynctask. &NBSP;2, time-consuming tasks must be handled in Doinbackground (), not in other callback methodsHandle time-consuming tasks to avoid blocking the main thread of the UI.  3, do not update the UI interface in Doinbackground (), the UI should be updated with the callback method called by Publishprogress ().  4, oncancelled () can only trigger the Cancel () method of Asynctask, and cannot cancel the thread task that is running on the thread pool, but can stop the thread task through the flag bit.  5, in different versions of Android, Asynctask multitasking, some of which can be parallel or sequential, but in high-version Android, the thread pool execution rules can be set by specifying parameters.  6, Asynctask is suitable for short-term operation, long-term operation, such as downloading a large video, which requires you to use your own threads to download, whether it is a breakpoint download or other.

[]android: Application of Asynctask for asynchronous Processing (ii)

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.