Android multithreaded analysis: Download images asynchronously using thread

Source: Internet
Author: User

Android multithreaded analysis: Download images asynchronously using thread

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

I'm going to tidy up the understanding of multithreading in the Android framework, focusing on the thread of the framework layer, Handler, Looper, MessageQueue, Message, Aysnctask, of course, inevitably. To refer to the native method, it also parses Dalvik and threading and message-handling related code such as the C + + thread class in Dalvik and the MessageQueue class. This article starts with a simple application that uses thread, introduces thread, and the next few articles describe the topics mentioned earlier.


This is a simple example of using Android Thread 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";p rivate static final int msg_load_success = 0;private static final int msg_load_failure = 1;    Private Button Mloadbutton;    Private ProgressDialog Mprogressbar;    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 ()") Mprogressbar = new ProgressDialog (this); Mprogressbar.setcancelable (true); Mprogressbar.setmessage ("Image downloading ..."); Mprogressbar.setprogressstyle (progressdialog.style_horizontal); Mprogressbar.setmax (+); 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) {mprogressbar.setprogress (0); Mprogressbar.show ();New Thread () {@OverridePublic void Run () {LOG.I ("Load thread", ">> Run ()");                        Bitmap Bitmap = Loadimagefromurl (Simageurl); if (bitmap! = null) {Message msg = mhandler.obtainmessage (msg_load_success, bitmap); Mhandler.sendmessage (msg);} else {Message msg = mhandler.obtainmessage (msg_load_failure, NULL); Mhandler.sendmessage (msg);}}}.start (); }        });}

Loadimagefromurl is a static function that downloads Bitmap from the network:

    Static Bitmap Loadimagefromurl (String uil) {    Bitmap Bitmap = null;        try{            InputStream in = new Java.net.URL (simageurl). OpenStream ();            Bitmap = Bitmapfactory.decodestream (in);            In.close ();        }        catch (Exception e) {        e.printstacktrace ();        }        return bitmap;    }

Mhandler is the Handler of the main thread, which is the UI thread that handles messages:

    Handler mhandler= New Handler () {        @Override        handlemessage(Message msg) {        log.i ("UI thread", ">> Handlemessage ()");                    Switch (msg.what) {case            msg_load_success:            Bitmap Bitmap = (Bitmap) msg.obj;                Mimageview.setimagebitmap (bitmap);                                Mprogressbar.setprogress (+);                Mprogressbar.setmessage ("Image downloading success!");                Mprogressbar.dismiss ();                break;                            Case Msg_load_failure:                mprogressbar.setmessage ("Image downloading failure!");                Mprogressbar.dismiss ();            Break;}}    ;

Looking at the above code, when the Load button is clicked, an anonymous thread is created, and its start () is called to start the running thread, the image is downloaded in this thread and decoded into Bitmap, and then a message is sent through Handler to the UI thread to notify the download result. This is all handled in an anonymous Thead. The main thread, which is the UI thread that receives the message, is distributed to Handler, which processes the download results based on the message ID in its Handlemessage method, either succeeds or fails, and updates the UI accordingly.


Run the example:


The thread IDs of the UI thread (tid:817) and Load thread (tid:830) can be seen from the fourth column of Logcat because they are two separate threads.


After the anonymous thread has been downloaded, why not update the UI directly in the thread's run ()? What is the consequence of this? These questions will be answered in detail later in this 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.