Android asynchronous download of network images (Part 1)

Source: Internet
Author: User

Projects sometimes need to obtain images on the network and download them to the mobile client for display. How can this problem be solved?

The implementation logic is as follows:

1: Enable a thread in the UI thread to download images.

2: After the image is downloaded, a message is sent to notify the UI thread.

2: After the UI thread obtains the message, it updates the UI.

The UI thread here is the main thread.

These two steps involve some knowledge points: progressdialog, handler, thread/runnable, URL, httpurlconnection, and so on.

Now let's start to implement this function!

Step 1: Create a project.

Step 2: design the UI as follows:

View code

 <?  XML version  =  "  1.0  "  Encoding =  "  UTF-8  "  ?>  
< Linearlayout xmlns: Android = " Http://schemas.android.com/apk/res/android "
Android: Orientation = " Vertical "
Android: layout_width = " Fill_parent "
Android: layout_height = " Fill_parent "
>
< Button
Android: ID = " @ + ID/btnfirst "
Android: layout_width = " Fill_parent "
Android: layout_height = " Wrap_content "
Android: Text = " Asynchronous download method 1 "
>
</ Button >

< Button
Android: ID = " @ + ID/btnsecond "
Android: layout_width = " Fill_parent "
Android: layout_height = " Wrap_content "
Android: Text = " Asynchronous download method 2 "
>
</ Button >

< Framelayout
Android: layout_width = " Fill_parent "
Android: layout_height = " Match_parent "
Android: ID = " @ + ID/framelayout "
>

< Imageview
Android: ID = " @ + ID/Image "
Android: layout_width = " Match_parent "
Android: layout_height = " Match_parent "
Android: scaletype = " Centerinside "
Android: padding = " 2dp "
>
</ Imageview >

< Progressbar
Android: ID = " @ + ID/progress "
Android: layout_width = " Wrap_content "
Android: layout_height = " Wrap_content "
Android: layout_gravity = " Center " >
</ Progressbar >

</ Framelayout >
</ Linearlayout >

Step 3: Obtain the view component of the UI and add event listening.

View code

 Public     Class  Downloaderactivity  Extends  Activity  Implements  Onclicklistener {
Private Static Final String Params = " Http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Hukou_Waterfall.jpg/800px-Hukou_Waterfall.jpg " ;
Private Button btnfirst, btnsecond;
Private Progressbar progress;
Private Framelayout;
Private Bitmap bitmap = Null ;
Progressdialog Dialog = Null ;


@ Override
Public Void Oncreate (bundle savedinstancestate ){
Super . Oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

Btnfirst = (Button) This . Findviewbyid (R. Id. btnfirst );
Btnsecond = (Button) This . Findviewbyid (R. Id. btnsecond );
SS = (Progressbar) This . Findviewbyid (R. Id. Progress );
Progress. setvisibility (view. Gone );
Framelayout = (Framelayout) This . Findviewbyid (R. Id. framelayout );

Btnfirst. setonclicklistener ( This );
Btnsecond. setonclicklistener ( This );
}

Step 4: process our logic in the listener event, that is, download the image data on the server.

Here we need to explain.

We usually use another thread to perform some time-consuming operations, such as downloading and uploading images, reading large volumes of XML data, and reading large volumes of SQLite data. Why? The answer is as follows.

Here, I first construct a progress bar dialog box to display the download progress, and then open a thread to download image data. After the data is downloaded, the main UI thread is notified to update and display our images.

Handler is a bridge between activity and thread/runnable. Handler is running in the main UI thread. It and the sub-thread can transmit data through the message object. DetailsCodeAs follows:

View code

    /**  Here, the handlemessage method is rewritten, And the UI is updated after the sub-thread data is received *  */  
Private Handler = New Handler (){
@ Override
Public Void Handlemessage (Message MSG ){
Switch (Msg. What ){
Case 1 :
// Close
Imageview View = (Imageview) framelayout. findviewbyid (R. Id. Image );
View. setimagebitmap (Bitmap );
Dialog. Dismiss ();
Break ;
}
}
};

The progress dialog box is displayed, where HTTP is used to obtain data.

View code

 //  The front-end UI thread is displaying progressdialog,
// The background thread is downloading data. After the data is downloaded, the Progress box is closed.
@ Override
Public Void Onclick (view ){
Switch (View. GETID ()){
Case R. Id. btnfirst:
Dialog = Progressdialog. Show ( This , "" ,
" Download data. Please wait... " , True , True );
// Start a background thread
Handler. Post ( New Runnable (){
@ Override
Public Void Run (){
// Download data here
Try {
URL = New URL (Params );
Httpurlconnection Conn = (Httpurlconnection) URL. openconnection ();
Conn. setdoinput ( True );
Conn. Connect ();
Inputstream = Conn. getinputstream ();
Bitmap = Bitmapfactory. decodestream (inputstream );
Message msg = New Message ();
MSG. What = 1 ;
Handler. sendmessage (MSG );

} Catch (Malformedurlexception E1 ){
E1.printstacktrace ();
} Catch (Ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
});
Break ;

So far, you will find that our download target has been successfully completed, and you can apply it to other aspects.

Run the following command:

 

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.