Android Development Learning Path-asynchronous operation with Asynctask

Source: Internet
Author: User

In general, we want to implement asynchronous operations, that is, time-consuming operations on child threads such as downloading or loading pictures, and then updating the UI in the UI (main) thread, using handler and message for asynchronous implementations, but Google's official Android system in fact encapsulated this approach, which is asynctask.

Use of handler and message: http://www.cnblogs.com/Fndroid/p/5098405.html

With Asynctask, you must create a new class that inherits from Asynctask and formulates incoming parameter types, describes procedure types, and return value types, which are generic

Next, you need to rewrite some methods, commonly used in the following:

OnPreExecute (): This method is executed before asynchronous loading, and is typically used to display a message box with the latter hint

Doinbackground (): This method is performed in a sub-thread, and all time-consuming operations, such as downloading or loading, can be performed here

Onprogressupdate (): This method is executed when the Publishprogress () method is executed in the Doinbackground method, and the Publishprogress () method passes some parameters that describe the procedure to this method. For example, using integer to describe the progress of the download

OnPostExecute (): This method executes after the Doinbackground () method has finished executing, judging how the UI should be updated according to the type of return

In the above method, only the Doinbackground () method is executed in the child thread, others are in the UI thread, so the UI can be updated directly.

Here we simulate a download, update the ListView after the download is complete, and toast if the download fails

1  Public classMainactivityextendsActivity {2 3     PrivateButton start;4     PrivateProgressDialog ProgressDialog;5     PrivateListView Mlistview;6     PrivateSimpleadapter Madapter;7     PrivateList<map<string, object>>mlist;8 9 @OverrideTen     protected voidonCreate (Bundle savedinstancestate) { One         Super. OnCreate (savedinstancestate); A Setcontentview (r.layout.activity_main); -Start =(Button) Findviewbyid (R.id.start); -Mlistview =(ListView) Findviewbyid (R.id.listview); theProgressDialog =NewProgressDialog ( This);//build a progressdialog to prompt for download information -Progressdialog.settitle ("Downloading data"); -Progressdialog.setmessage ("Download ..."); -Progressdialog.setcancelable (true); +Start.setonclicklistener (NewOnclicklistener () { - @Override +              Public voidOnClick (View v) { A                 NewDownLoad (). Execute (); at             } -         }); -     } -  -     //a asynctask subclass defined here, the input parameter type is empty, the procedure indicates that the parameter is an integer type, the asynchronous return type is Boolean -     classDownLoadextendsAsynctask<void, Integer, boolean> { in @Override -         protected voidOnPreExecute () { toProgressdialog.show ();//before starting an asynchronous download, display the ProgressDialog, prompting you are downloading +         } -  the @Override *         protectedBoolean doinbackground (Void ... params) { $             Try {Panax Notoginseng                  for(inti = 1; I <= 5; i++) {//perform a publishprogress every 500 milliseconds and put the parameters in. -Thread.Sleep (500); thePublishprogress (i * 20); +                 } A}Catch(interruptedexception e) { the e.printstacktrace (); +             } -Random rd =NewRandom (); $             intRandomint = Rd.nextint (10); $             if(randomint% 2 = = 0) {//generates a random number, or if it is even, return true indicates that the download was successful and the odd expression failed -                 return true; -}Else { the                 return false; -             }Wuyi         } the  - @Override Wu         protected voidonprogressupdate (Integer ... values) { -LOG.E ("Asynctask", "progress=" + values[0] + "%");//triggered after publishprogress execution, a value of the parameter is the parameter passed in the Publishprogress . About         } $  - @Override -         protected voidOnPostExecute (Boolean result) { - Progressdialog.dismiss (); A             //determine if the download succeeds, update the ListView, and then toast the failure . +             if(Result) { theMlist =NewArraylist<map<string, object>>(); -                  for(inti = 0; I < 50; i++) { $map<string, object> map =NewHashmap<string, object>(); theMap.put ("string", "Hello"); the mlist.add (map); the                 } theMadapter =NewSimpleadapter (Getapplicationcontext (), Mlist, - Android. R.layout.simple_list_item_1, in                         NewString[] {"string" }, the                         New int[] {Android. R.ID.TEXT1}); the Mlistview.setadapter (madapter); About}Else { theToast.maketext (Getapplicationcontext (), "Download error!", the toast.length_short). Show (); the             } +         } -  the     }Bayi  the}

Show:

Log:

You can see that the time is every 500 milliseconds, and the onprogressupdate () function executes once.

Android Development Learning Path-asynchronous operation with Asynctask

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.