Android multi-thread Analysis 5: Use AsyncTask to asynchronously download images

Source: Internet
Author: User

Android multi-thread Analysis 5: Use AsyncTask to asynchronously download images
Android multi-thread Analysis 5: Use AsyncTask to asynchronously download images

 

In the first article in this series, "Android multi-Thread analysis: downloading images asynchronously using threads", we demonstrated how to use threads to complete asynchronous tasks. Android implements a template class named AysncTask to simplify asynchronous tasks in the UI thread (after all, the UI thread is the most important thread of the app. You can use AysncTask to report the task progress to the UI thread (for example, to update the progress bar of the UI thread) while performing asynchronous tasks ). Because it is closely related to the UI thread, there must be some restrictions when using it. AysncTask must be created in the UI thread and started in the UI thread (by calling its execute () in addition, AysncTask is designed to be used for some time-consuming tasks. If it is a time-consuming task, AysncTask is not recommended.

You can use simplified memory"Three parameters and four stepsTo learn about AysncTask. Contains three template parameters. , Four processing steps: onPreExecute, doInBackground, onProgressUpdate, onPostExecute.

Three parameters:

Params is the parameter type required for an asynchronous task, that is, doInBackground (Params... params) parameter type of the method; Progress refers to the parameter type of the Progress, that is, onProgressUpdate (Progress... values) parameter type of the method;
Result indicates the type of the parameter returned after the task is completed, that is, the parameter type of the onPostExecute (Result) or onCancelled (result) method.

If a parameter type is meaningless or not used, pass void.

Step 4:

Protected void onPreExecute (): runs in the UI thread and is executed before the asynchronous task starts, so that the UI thread can complete some initialization actions, such as clearing the progress bar;
Protected abstract Result doInBackground (Params... params): runs in the background thread. This is where the asynchronous task is completed. It is an abstract interface and must be implemented by a subclass;
Protected void onProgressUpdate (Progress... values): run in the UI thread. During asynchronous task execution, you can call void publishProgress (Progress... values) method notifies the UI thread to update the progress status in the onProgressUpdate method;
Protected void onPostExecute (Result result): runs in the UI thread and is executed after the asynchronous task is completed, so that the UI thread can update the task completion status.

AysncTask supports canceling asynchronous tasks. After an asynchronous task is canceled, the preceding step 4 will not be executed. Instead, the onCancelled (Result result) will be executed ), this allows the UI thread to update the status after the task is canceled. Remember: all the methods mentioned above are callback functions and do not need to be manually called.

Previously, AysncTask was implemented based on a single background thread, while from Android 3.0 onwards AysncTask was implemented based on Android concurrent Library (java. util. concurrent), this article will not discuss its specific implementation, just demonstrate how to use AysncTask.

Example:

With the previous outline introduction, it is very easy to use AysncTask. The example below is very similar to the example in "Using Thread to download images asynchronously, however, AysncTask is used to complete asynchronous tasks.

This is a simple example of using AysncTask to asynchronously download images from the network and display them in ImageView. To access the network, add the network access permission to manifest. xml:

 

The layout file is simple, with a Button and an ImageView:

 

 
  
   
 

 

Next, let's look at the Code:

First, let's look at the definition: the url path of the image, two message values and some controls:

    private static final String sImageUrl = http://fashion.qqread.com/ArtImage/20110225/0083_13.jpg;    private Button mLoadButton;    private ImageView mImageView;

Then let's look at the control settings:

 

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.i(UI thread,  >> onCreate());mImageView = (ImageView)this.findViewById(R.id.ImageVivew);mLoadButton = (Button)this.findViewById(R.id.LoadButton);mLoadButton.setOnClickListener(new View.OnClickListener() {            @Override             public void onClick(View v) {            LoadImageTask task = new LoadImageTask(v.getContext());                task.execute(sImageUrl);            }        });}

LoadImageTask inherits from AysncTask. This class completes the asynchronous image download task and updates the UI status accordingly.

 

 

class LoadImageTask extends AsyncTask
 
   {private ProgressDialog mProgressBar;    LoadImageTask(Context context){mProgressBar = new ProgressDialog(context);mProgressBar.setCancelable(true);mProgressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);mProgressBar.setMax(100);}@Overrideprotected Bitmap doInBackground(String... params) {Log.i(Load thread,  >> doInBackground());Bitmap bitmap = null;try{publishProgress(10);Thread.sleep(1000);            InputStream in = new java.net.URL(sImageUrl).openStream();            publishProgress(60);Thread.sleep(1000);            bitmap = BitmapFactory.decodeStream(in);            in.close();            } catch (Exception e) {            e.printStackTrace();}publishProgress(100);return bitmap;}@Overrideprotected void onCancelled() {            super.onCancelled();        }     @Override        protected void onPreExecute() {mProgressBar.setProgress(0);    mProgressBar.setMessage(Image downloading ... %0);    mProgressBar.show();        Log.i(UI thread,  >> onPreExecute());        }         @Override        protected void onPostExecute(Bitmap result) {    Log.i(UI thread,  >> onPostExecute());    if (result != null) {    mProgressBar.setMessage(Image downloading success!);        mImageView.setImageBitmap(result);    }    else {    mProgressBar.setMessage(Image downloading failure!);    }            mProgressBar.dismiss();         }           @Overrideprotected void onProgressUpdate(Integer... values) {   Log.i(UI thread,  >> onProgressUpdate() % + values[0]);   mProgressBar.setMessage(Image downloading ... % + values[0]);   mProgressBar.setProgress(values[0]);}};
 

 

In LoadImageTask, the four steps mentioned above involve:

First, set the initial status (UI thread) of the progress bar in the onPreExecute () method before the task starts. Then, execute doInBackground () in the download thread to complete the download task, publishProgress () is called to notify the UI thread of the update progress state. The UI thread learns the progress in onProgressUpdate () and updates the progress bar (UI thread). The download task is completed, the UI thread learns the downloaded image in onPostExecute () and updates the UI to display the image (UI thread ).

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.