Android example tutorial on using Asynctask classes to make cool progress bars _android

Source: Internet
Author: User

Asynctask (API level 3, so almost all current versions of Android available on the market)
As an alternative to Thread, the Android team encourages the main thread (UI Thread) to focus on the smooth presentation of operations & images,
The rest of the work (such as network data transmission, File/disk/data access) is best done in the background;
Thread is usually used in combination with Handler, and Asynctask is intended to perform thread code writing in a simplified background.

If you expect the work to be done in a matter of seconds, you can choose to use Asynctask, and if it takes a long time to execute,
Android is strongly advised to use Executor, Threadpoolexecutor and Futuretask.

To use Asynctask, you must establish a subcategory that inherits from Asynctask and pass in 3 items:

    • Params-The number of arguments passed in to perform doinbackground () can be more than one
    • Progress--The amount of data that is passed back to UI thread during the execution of Doinbackground () can be more than one
    • Rsesult--Returns execution results

If you do not have a parameter to pass in, Void is filled (note that V is uppercase).

The operation of Asynctask has 4 stages:

    • OnPreExecute-Asynctask preparation before execution, such as displaying a progress meter on the screen,
    • Doinbackground--The actual code to execute is written here,
    • Onprogressupdate--to show the current progress,
    • OnPostExecute--results are passed in here.

In addition to Doinbackground, the other 3 method is called in the UI thread


Cool Progress Bar Example
We use an example to illustrate, "Click the button to start downloading the Qqandroid installation package, and then display a dialog box to feedback the download progress." We first initialize a dialog box, because we want to show progress, we use GitHub above a can show the percentage of the progress bar Numberprogressbar, start the task of the button we use Circlebutton, a cool animation button, GitHub There are many very good open source projects, of course, cool control is part of it, there are opportunities behind, will go to learn some of the more popular control of their implementation principle, today for the time being copycat ~ ~.

1. First initialize the progress Bar prompt dialog box.

 Builder = new Alertdialog.builder (
     mainactivity.this);
 Layoutinflater inflater = Layoutinflater.from (mainactivity.this);
 Mdialogview = inflater.inflate (r.layout.progress_dialog_layout, null);
 Mnumberprogressbar = (Numberprogressbar) Mdialogview.findviewbyid (R.id.number_progress_bar);
 Builder.setview (Mdialogview);
 Mdialog = Builder.create ();

2. Set button click event.

 Findviewbyid (R.ID.CIRCLE_BTN). Setonclicklistener (New View.onclicklistener () {
   @Override public
   Void OnClick (View v) {
     dismissdialog ();
     Mnumberprogressbar.setprogress (0);
     MyTask = new Myasynctask ();
     Mytask.execute (Qqdownloadurl);
   }
 );

3.DownloadAsyncTask implementation, a bit long.

Private class Downloadasynctask extends Asynctask<string, Integer, string> {@Override protected void onpreexec
   Ute () {super.onpreexecute ();

 Mdialog.show ();
   } @Override protected void OnPostExecute (String avoid) {super.onpostexecute (avoid);
 DismissDialog ();

   } @Override protected void Onprogressupdate (Integer ... values) {super.onprogressupdate (values);
 Mnumberprogressbar.setprogress (Values[0]);
   } @Override protected void oncancelled (String avoid) {super.oncancelled (avoid);
 DismissDialog ();
   } @Override protected void oncancelled () {super.oncancelled ();
 DismissDialog ();
   @Override protected string Doinbackground (String ... params) {string urlstr = Params[0];
   FileOutputStream output = null;
     try {URL url = new URL (urlstr);
     HttpURLConnection connection = (httpurlconnection) url.openconnection ();
     String qqapkfile = "Qqapkfile"; File File = new file (environment.getexternalstoragedirectory () + "/" + Qqapkfile);
     if (file.exists ()) {file.delete ();
     } file.createnewfile ();
     InputStream input = Connection.getinputstream ();
     Output = new FileOutputStream (file);
     int total = Connection.getcontentlength ();
     if (total <= 0) {return null;
     int plus = 0;
     int totalread = 0;
     byte[] buffer = new byte[4*1024];
       while (plus = input.read (buffer))!=-1) {output.write (buffer);
       Totalread + = plus;
       Publishprogress (Totalread * 100/total);
       if (iscancelled ()) {break;
   } output.flush ();
     catch (Malformedurlexception e) {e.printstacktrace ();
       if (output!= null) {try {output.close ();
       catch (IOException E2) {e2.printstacktrace ();
     A catch (IOException e) {e.printstacktrace ());
       if (output!= null) {try {output.close (); catch (IOException E2) {e2.printstacktrace ();
       Finally {if (output!= null) {try {output.close ()}}}
       catch (IOException e) {e.printstacktrace ();
 }} return null;

 }
}

Such a simple download file is basically implemented, so far not a trick, but now we have a problem is that if our activity is in the background to perform a task, it may take a long time, the user may click to return to quit the event or quit the app, Then the background task does not exit immediately, if the Asynctask internal activity in the member variable reference, will also cause activity recovery delay, resulting in a period of memory leaks, so we need to add the following fourth step processing.

The 4.onPause determines whether the application is to exit, thereby determining if Asynctask execution is canceled.

@Override
protected void OnPause () {
 super.onpause ();
 if (mytask!= null && isfinishing ()) {
   mytask.cancel (false);
 }
}

So that our asynchronous task will be when the activity exits, also with the cancellation of task execution, successfully destroyed by the system recovery, the fourth step many times will be omitted, and generally will not have any fatal problems, but once the problem, it is difficult to troubleshoot, so follow the coding code is still necessary.


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.