Detailed explanation of Asynctask asynchronous task execution in Android app _android

Source: Internet
Author: User

Basic concepts

Asynctask: Asynchronous tasks, literally, are done asynchronously while our UI main thread is running. Asynctask allows us to perform an asynchronous task in the background. We can execute time-consuming operations in asynchronous tasks and return the results of our task execution to our UI thread to update our UI controls. Through Asynctask we can easily solve the problem of communication between multithreading.

How to understand Asynctask? In layman's terms, Asynctask is equivalent to Android provides us with a framework for multithreaded programming, between thread and handler, and if we want to define a asynctask, we need to define a class to inherit asynctask this abstract class , and implements its only one Doinbackgroud abstract method. To master Asynctask, we must have a concept, summed up is: 3 generics, 4 steps.

What does 3 generics mean? Let's look at Asynctask's definition of this abstract class, and when we define a class to inherit asynctask this class, we need to specify 3 generic parameters for it:

Asynctask <params, Progress, result>

    • Params: This generic type specifies the type of arguments we pass to the asynchronous task execution
    • Progress: This generic specifies the type of parameters that our asynchronous task will perform at the time it is executed to the UI thread
    • Result: The type of results returned to the UI thread after the asynchronous task specified by this generic type

When we define a class to inherit the Asynctask class, we must specify the type of the three generic types, and if not, write them void, for example:

Asynctask <void, Void, void>
4 steps: When we perform an asynchronous task, it needs to follow the following 4 steps to execute

    • OnPreExecute (): This method is performed before the asynchronous task is performed and is performed in UI thread, where we typically do some initialization of the UI controls, such as pop-up to ProgressDialog
    • doinbackground (Params ... Params): After the OnPreExecute () method executes, this method is executed immediately, which is the method that handles the asynchronous task. The Android operating system will open a worker thread in the background thread pool to execute our method, so this method is executed in worker thread, and after this method is executed we can send our execution results to our last OnPostExecute method, in this method, we can get data from the network and other time-consuming operations
    • onprogressupdate (progess ... values): This method is also implemented in UI thread, When we perform asynchronous tasks, we sometimes need to return the progress of execution to our UI interface, such as downloading a picture of the web, and we need to show the progress of the download at all times, and we can use this method to update our progress. Before this method is invoked, we need to call a publishprogress (Progress) method in the Doinbackground method to pass our progress all the time to the Onprogressupdate method to update the
    • OnPostExecute (Result ... results): When our asynchronous task is finished, we return it to this method, which is also invoked in UI thread, and we can display the returned results on the UI control

Why does our asynctask abstract class have only one Doinbackground abstract method?? The reason is that if we're going to do an asynchronous task, we have to create a new thread for it to do something, and when I do this asynchronous task, I probably don't need to pop up to ProgressDialog, I don't need to update my ProgressDialog progress bar at any time, and I don't need to update the results to our UI interface, so three methods other than the Doinbackground method are not necessary, so the way we have to implement it is Doinbackground method.

Instance
here is a demo that opens a network picture:

Package com.app.main;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.impl.client.DefaultHttpClient;
 
Import Org.apache.http.util.EntityUtils;
Import Android.annotation.SuppressLint;
Import android.app.Activity;
Import Android.app.ProgressDialog;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.os.AsyncTask;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
 
Import Android.widget.ImageView; public class Main extends activity {String URL = ' Http://e.hiphotos.baidu.com/image/w%3D2048/sign=61711bd121a446237ec
  Aa262ac1a730e/e850352ac65c10385f10af69b3119313b07e892a.jpg ";
  ImageView Imgview = null;
  Button btn = null;
 
  ProgressDialog dialog = null; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (SAVedinstancestate);
 
    Setcontentview (R.layout.main);
    Imgview = (ImageView) This.findviewbyid (R.id.imageview);
    BTN = (Button) This.findviewbyid (R.ID.BTN);
    dialog = new ProgressDialog (this);
 
    Dialog.setmessage ("Download picture ..."); Btn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (view view) {New Myta
      SK (). Execute (URL);
 
  }
 
    });
 
      Class MyTask extends asynctask<string, void, bitmap> {@Override protected void OnPreExecute () {
 
      Super.onpreexecute ();
 
    Dialog.show ();
 
      } @Override protected Bitmap doinbackground (String ... params) {Bitmap Bitmap = null;
 
      String URL = params[0];
 
      HttpClient client = new Defaulthttpclient ();
 
      HttpGet GetMethod = new HttpGet (URL);
 
        try {httpresponse response = Client.execute (GetMethod); if (Response.getstatusline (). Getstatuscode () = = httpentity Entity = ResponSe.getentity ();
 
          byte[] data = Entityutils.tobytearray (entity);
 
        Bitmap = bitmapfactory. Decodebytearray (data, 0, data.length);
    The catch (Exception e) {} return bitmap; @SuppressLint ("Newapi") @Override protected void OnPostExecute (Bitmap result) {Super.onpostexecut
 
      E (Result);
 
      Imgview.setimagebitmap (result);
    Dialog.dismiss ();
 }
 
  }
 
}

The effect of the implementation is as shown in figure:

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.