One of the Android multithreaded analysis: Download images asynchronously using thread

Source: Internet
Author: User

One of the Android multithreaded analysis: Download images asynchronously using thread

Roche (Http://blog.csdn.net/kesalin)CC License. Reprint please indicate the source

Plan to get an understanding of multithreading-related knowledge in the Android Framework. The main focus in the Framework layer of thread, Handler, Looper, MessageQueue, message, Aysnctask, of course, is inevitably related to the native method, so it will also analyze Dalvik and threads as well as the message Code such as the C + + Thread class in Dalvik and the MessageQueue class. This article starts with a simple application that uses Thread. Introduce thread to this topic. The next few articles will describe the topics mentioned earlier.


This is a simple demo sample that uses Android Thread to download images asynchronously from the network and display them in ImageView.

Because of the need to access the network, so you want to add network visiting permission in Manifest.xml:

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

Layout files are very easy, 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;}}    ;

Throughout the code above. When the load button is clicked, an anonymous thread is created and its start () is called to start the execution thread, where the image is downloaded and decoded into Bitmap. A message is then sent to the UI thread through Handler to notify the download result. This is all handled in an anonymous Thead. The main thread is when the UI thread receives the message. is distributed to Handler, and the download results are processed in its Handlemessage method based on the message ID. Either success or failure. and update the UI accordingly.


Perform the Demo sample:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqva2vzywxpbg==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "/>

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


After the anonymous thread has finished downloading, why not update the UI directly in the thread's run ()? What is the consequence of this? These questions will be answered in detail in the following article.


One of the Android multithreaded analysis: Download images asynchronously using thread

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.