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". demonstrated how to use Thread to complete an asynchronous task.

Android in order to simplify the completion of the asynchronous task in the UI thread (after all, the UI thread is the most important thread of the app). A template class named Aysnctask is implemented. Use Aysnctask to feed the task progress status back to the UI thread (such as letting the UI thread update the progress bar) at the same time as the asynchronous task. It is because it is closely related to the UI thread that there are some limitations when using it. Aysnctask must be created in the UI thread. and starts in the UI thread (by calling its execute () method). In addition, the Aysnctask design is intended for some time-consuming tasks, assuming that Aysnctask is not recommended for long-time tasks.

Can be used to simplify the memory of "three parameters." Four steps "to learn aysnctask.

That is, with three template parameters <params, Progress, result>. Four processing steps: OnPreExecute. Doinbackground,onprogressupdate,onpostexecute.

Three-parameter:

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 is the type of the parameter returned by the completion of the task, that is, the onpostexecute (result result) or oncancelled (result result) method.

Assume that a certain parameter type is meaningless or not used. passing void is possible.

Four steps:

protected void OnPreExecute (): Runs in the UI thread. Run before the asynchronous task starts so that the UI thread finishes some initialization actions, such as zeroing the progress bar.
Protected abstract Result doinbackground (params ... params): Runs in a background thread. This is where the asynchronous task ends and it is an abstract interface. Subclasses must provide implementations;
protected void Onprogressupdate (Progress ... values): Runs in the UI thread. You can notify the UI thread to update the progress status within the Onprogressupdate method by calling the void Publishprogress (Progress. Values) method during the asynchronous task's run.
protected void OnPostExecute (result result): Runs in the UI thread and is run when the asynchronous task is complete 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 will not be run, instead run oncancelled (result result) so that the UI thread updates the state after the task is canceled.

Remember: The above mentioned methods are callback functions and do not need to be manually called by the user.

The Aysnctask was implemented based on a single background thread. Since Android 3.0 Aysnctask is based on the Concurrent Android Library (java.util.concurrent), this article does not discuss its detailed implementation, just to demonstrate how to use the Aysnctask.

Use the Demo sample:

With the introduction of the previous outline, and then to use the Aysnctask is very easy, the following example is similar to the example in "using thread to download images asynchronously", just to use Aysnctask to complete the asynchronous task.

This is a simple demo sample that uses Aysnctask to download images asynchronously from the network and display them in ImageView. Because of the need to access the network. So to add network access in Manifest.xml:

<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. This class goes through 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 the Loadimagetask. The four steps mentioned above are related to:

First set the initial state of the progress bar (UI thread) in the OnPreExecute () method before the task starts. Then run Doinbackground () in the download thread to complete the download task. Publishprogress () is called to notify the UI thread to update the progress status, the UI thread learns the progress in Onprogressupdate () and updates the progress bar (UI thread), and the last download task finishes, the UI thread is in the OnPostExecute () and update 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.