Android Multithreading analysis V: Download images asynchronously using Asynctask

Source: Internet
Author: User

Android Multithreading analysis V: Download images asynchronously using Asynctask

Roche (Http://blog.csdn.net/kesalin) CC License, reproduced please specify the source

In the first article in this series, "one of the Android multithreaded analysis: Using thread to download images asynchronously," demonstrates how to use thread to complete an asynchronous task. Android to simplify the task of completing asynchronous tasks in the UI thread (after all, the UI thread is the most important thread for the app), implements a template class named Aysnctask. You can use Aysnctask to feed the progress status of a task to the UI thread (such as letting the UI thread update the progress bar) while the asynchronous task progresses. It is because it is closely related to the UI thread that when used there are some limitations, aysnctask must be created in the UI thread and started in the UI thread (by calling its execute () method), and the Aysnctask design is designed to be used for some short-time tasks, It is not recommended to use Aysnctask if it is a long time task.

You can use the simplified memory " three parameters, four steps " to learn aysnctask. That is, with three template parameters <params, Progress, result>, four processing steps: Onpreexecute,doinbackground,onprogressupdate,onpostexecute.

Three parameters:

The Params is the type of parameter required for an asynchronous task, which is the parameter type of the Doinbackground (params. params) method; Progress refers to the parameter type of the progress, that is, the onprogressupdate (Progress ... Values) The parameter type of the method;
Result refers to the type of the parameter returned by the task completion, which is the parameter type of the OnPostExecute (result result) or oncancelled (result result) method.

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

Four steps:

protected void OnPreExecute (): Runs in the UI thread and is executed before the asynchronous task starts so that the UI thread completes some initialization actions, such as clearing the progress bar by 0;
Protected abstract Result doinbackground (params ... params): Runs in a background thread, where the asynchronous task is completed, it is an abstract interface, and the subclass must provide the implementation;
protected void Onprogressupdate (Progress ... values): Run in the UI thread, which can be called by calling void Publishprogress (Progress ...) during the execution of the asynchronous task. Values) method notifies the UI thread to update the progress status within the Onprogressupdate method;
protected void OnPostExecute (result result): Runs in the UI thread and is executed after the asynchronous task completes so that the UI thread updates the task completion state.

Aysnctask supports canceling an asynchronous task, and when the asynchronous task is canceled, step four above is not executed, instead the oncancelled (result result) is executed so that the UI thread updates the state after the task is canceled. Remember: The above mentioned methods are callback functions and do not require the user to call them manually.

The previous aysnctask was implemented based on a single background thread, and the Android 3.0 Aysnctask is based on the Concurrency Library (java.util.concurrent), which is not discussed in this article, but demonstrates how to use Aysnctask.

Examples of Use:

With the introduction of the previous outline, it is very easy to use the Aysnctask, and the following example is very similar to the example in "using thread to download images asynchronously", but using Aysnctask to accomplish asynchronous tasks.

This is a simple example of using Aysnctask to download images asynchronously from the network and display them in ImageView. To add network access in Manifest.xml because you need to access the network:

<uses-permission android:name= "Android.permission.INTERNET" ></uses-permission>

The layout file is simple, a Button, a ImageView:

<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"    android:padding= "10dip" ><buttonandroid:id= "@+id/loadbutton" Android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "Load" ></Button> <imageviewandroid:id= "@+id/imagevivew" android:layout_width= "match_parent" android:layout_height= "400dip" Android:scaletype= "Centerinside" android:padding= "2DP" ></ImageView> </LinearLayout>

Next look at the code:

Let's start with the definition: the URL path to the picture, 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 look at the settings for the control:

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, which completes the asynchronous picture download task and updates the UI state accordingly.

Class Loadimagetask extends Asynctask<string, Integer, bitmap> {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 (+); 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 earlier involve:

First set the initial state of the progress bar (UI thread) in the OnPreExecute () method before the task starts, and then execute Doinbackground () in the download thread to complete the download task and call Publishprogress () in it to notify the UI The thread updates the progress status, the UI thread learns the progress in Onprogressupdate (), updates the progress bar (UI thread), the last download task finishes, the UI thread learns the downloaded image in OnPostExecute (), and updates the UI to display the image (UI thread).

Android Multithreading analysis V: Download images asynchronously using Asynctask

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.