"Android Basics" asynctask example--load network pictures

Source: Internet
Author: User

Network operations are a serious time-consuming operation, so starting with Android 4.0, network operations are strictly prohibited in the main thread, so network operations can only be placed in asynchronous tasks.

The following is an example of downloading a picture from the network, which is divided into two sections:
-Asynchronous processing of downloaded pictures
-Working with pictures in the UI thread

Download the image is in the Baidu image in the casual search: http://img1.ph.126.net/GPS04o8gJYuG4ZOwlx6UQA==/978125544087835399.jpg

First of all layout layouts, this is relatively simple, only need a imageview display picture and a ProgressBar to see if the download is complete, the code is as follows:

<relativelayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  xmlns:tools  =" Http://schemas.android.com/tools " android:id  = "@+id/relativelayout1"  android:layout_width  =" match_parent " android:layout_height  =" match_parent " android:padding  =" 14DP "  Tools:context  =;     <imageview  android:id
      = "@+id/imageview1"  android:layout_width  = "fill_parent"  android:layout_height  = "fill_parent"  android:layout_alignparentleft  = android:layout_alignparenttop  =/>     <ProgressBarandroid:id= "@+id/progressbar1"android:visibility=" Gone "style="? Android:attr/progressbarstylelarge "android:layout_width=" Wrap _content "android:layout_height=" Wrap_content "android:layout_centerhorizontal ="true"android:layout_centervertical="true" />                                                        </relativelayout>

Be careful to set the ProgressBar to hidden:

Here is the code in Mainactivity:

 PackageCom.asynctasktest;ImportJava.io.BufferedInputStream;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.net.MalformedURLException;ImportJava.net.URL;ImportJava.net.URLConnection;ImportAndroid.graphics.Bitmap;ImportAndroid.graphics.BitmapFactory;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.ImageView;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.Toast; Public  class mainactivity extends actionbaractivity {PrivateImageView Mimageview =NULL;PrivateProgressBar Mprogressbar =NULL;PrivateString URL ="Http://img1.ph.126.net/GPS04o8gJYuG4ZOwlx6UQA==/978125544087835399.jpg";@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//Instantiation Control This. Mimageview = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1); This. Mprogressbar = (ProgressBar) Findviewbyid (R.ID.PROGRESSBAR1);//Instantiating asynchronous TasksImagedownloadtask task =NewImagedownloadtask ();//Perform asynchronous TasksTask.execute (URL);} Class Imagedownloadtask extends Asynctask<string,void,bitmap> {@OverrideprotectedBitmapDoinbackground(String ... params) {Bitmap Bitmap =NULL;//Results to be returnedString URL = params[0];//Get URLURLConnection connection;//Network Connection objectInputStream is;//Data input streamTry{connection =NewURL (URL). OpenConnection (); is = Connection.getinputstream ();//Get input streamBufferedinputstream buf =NewBufferedinputstream (IS);//Parse input streamBitmap = Bitmapfactory.decodestream (BUF); Is.close (); Buf.close ();}Catch(Malformedurlexception e) {//TODO auto-generated catch blockE.printstacktrace ();}Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace ();}//Return to the method called laterreturnBitmap;}@Overrideprotected void OnPreExecute() {//Show wait ringMprogressbar.setvisibility (view.visible);}@Overrideprotected void OnPostExecute(Bitmap result) {//Download complete, hide wait ringMprogressbar.setvisibility (View.gone); Mimageview.setimagebitmap (result);}}}

Finally, add network access to the Androidmanifest:

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

There is an inner class in mainactivity: Imagedownloadtask, which is used to download images of the specified URL and display the image in ImageView.
The internal class asynchronous processing part (that is, the Doinbackground method) as an asynchronous picture downloader, we pass in this downloader is the image URL, the downloader is the picture, and we do not need to know the picture loading progress, so the three generic parameters of the type string, void and bitmap.

When we start the asynchronous task, we first execute the OnPreExecute method, so we can display the ProgressBar in this method, and then start the sub-thread to execute the Doinbackground, and pass the parameters to this method, this method will do the network operation, Download the picture and turn it back to bitmap, return the child thread is finished, and finally execute the OnPostExecute method, this method gets the result of the asynchronous processing, that is, the download good picture, This method sets ImageView to download the good picture and hides the ProgressBar.

Here are the results after the download:

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android Basics" asynctask example--load network pictures

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.