Asynchronous acquisition and download of network resources for Android Development

Source: Internet
Author: User
Tags file url

Asynchronous acquisition and download of network resources for Android Development

1) Get the corresponding stream from the specified URL

 

To obtain network resources, you must first have a URL. Here, I first encapsulate an InputStream Stream Obtained by opening the URL Connection, in this way, you can use this interface to retrieve streams for image resources and text file resources.

 

This function is mainly implemented using URLConnection and HttpURLConnection. The specific implementation scheme is as follows:

 

Copy code

Private InputStream openHttpConnection (String urlString) throws IOException {

InputStream in = null;

Int response =-1;

URL url = new URL (urlString );

URLConnection conn = url. openConnection ();

If (! (Conn instanceof HttpURLConnection )){

Throw new IOException ("It is not an HTTP connection ");

}

Try {

HttpURLConnection httpConn = (HttpURLConnection) conn;

HttpConn. setAllowUserInteraction (false );

HttpConn. setInstanceFollowRedirects (true );

HttpConn. setRequestMethod ("GET ");

HttpConn. connect ();

Response = httpConn. getResponseCode ();

If (response = HttpURLConnection. HTTP_ OK ){

In = httpConn. getInputStream ();

}

} Catch (Exception ex ){

Log. v ("Networking", ex. getLocalizedMessage ());

Throw new IOException ("Error connecting ");

}

Return in;

}

Copy code

(2) After encapsulating the above method to obtain the stream, we can use the encapsulated method to obtain and download the corresponding image and text file content.

 

How to Get and download image resources:

 

Copy code

Private Bitmap downloadImage (String url ){

Bitmap bitmap = null;

InputStream in = null;

Try {

In = openHttpConnection (url );

Bitmap = BitmapFactory. decodeStream (in );

In. close ();

} Catch (IOException e ){

// TODO Auto-generated catch block

Log. v ("NetworkingActivity", e. getLocalizedMessage ());

}

Return bitmap;

}

Copy code

 

 

How to Get and Download text content:

 

Copy code

Private String downloadText (String url ){

Int BUFFER_SIZE = 2000;

InputStream is = null;

Try {

Is = openHttpConnection (url );

} Catch (IOException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

Return "";

}

InputStreamReader isr = new InputStreamReader (is );

Int charRead;

String str = "";

Char [] inputBuffer = new char [BUFFER_SIZE];

Try {

While (charRead = isr. read (inputBuffer)> 0 ){

String readString = String. copyValueOf (inputBuffer, 0, charRead );

Str + = readString;

InputBuffer = new char [BUFFER_SIZE];

}

Is. close ();

} Catch (IOException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

Return "";

}

Return str;

}

Copy code

(3) After obtaining and downloading image resources and text content resources, you can start the download task now. To prevent the wait effect, asynchronous tasks are generally used to download network resources.

 

Encapsulate the respective asynchronous download tasks for the corresponding download resource tasks. The following describes how to Implement Asynchronous download tasks:

 

Asynchronous image download task:

 

Copy code

Private class DownloadImageTask extends AsyncTask <String, Bitmap, Long> {

 

Long imagesCount = 0;

ProgressBar progressBar;

Public DownloadImageTask (ProgressBar pBar ){

This. progressBar = pBar;

}

@ Override

Protected Long doInBackground (String... urls ){

// TODO Auto-generated method stub

For (int I = 0; I <urls. length; I ++ ){

Bitmap imageDownloaded = downloadImage (urls [I]);

If (imageDownloaded! = Null ){

ImagesCount ++;

PublishProgress (imageDownloaded );

Try {

Thread. sleep (300 );

} Catch (InterruptedException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

}

}

Return imagesCount;

}

// Display the image downloaded

@ Override

Protected void onProgressUpdate (Bitmap... bitmaps ){

// TODO Auto-generated method stub

IvImg. setImageBitmap (bitmaps [0]);

ProgressBar. setProgress (int) imagesCount * 10 );

}

// When all the images have been downloaded

@ Override

Protected void onPostExecute (Long imageDownloaded ){

// TODO Auto-generated method stub

String str = "Download complete! A total of "+ imagesCount +" Images "have been downloaded ";

Toast. makeText (getBaseContext (), str, Toast. LENGTH_SHORT). show ();

}

}

Copy code

 

 

Asynchronous download of Text File Content task:

 

Copy code

Private class DownloadTextTask extends AsyncTask <String, Void, String> {

 

@ Override

Protected void onPostExecute (String result ){

// TODO Auto-generated method stub

Toast. makeText (getBaseContext (), result, Toast. LENGTH_LONG). show ();

}

 

@ Override

Protected String doInBackground (String... urls ){

// TODO Auto-generated method stub

Return downloadText (urls [0]);

}

}

Copy code

In this way, the asynchronous download of network resources is complete.

 

The following provides the URL of the network resource in the sample code of this Article for your convenience. The rest of the non-core code will not be posted. Sorry.

 

Copy code

// URL for image download

Private String [] mUrl =

{

"Http://images.cnitblog.com/ I /322919/201405/181111308592436.png ",

"Http://images.cnitblog.com/ I /322919/201405/181111385003770.png ",

"Http://images.cnitblog.com/ I /322919/201405/181111493901865.png ",

"Http://images.cnitblog.com/ I /322919/201405/181111550463327.png ",

"Http://images.cnitblog.com/ I /322919/201405/181117587961455.png ",

"Http://images.cnitblog.com/ I /322919/201405/181118041251414.png ",

"Http://images.cnitblog.com/ I /322919/201405/181119313754936.png ",

"Http://images.cnitblog.com/ I /322919/201405/181119357816682.png ",

"Http://images.cnitblog.com/ I /322919/201405/181119458753432.png ",

"Http://images.cnitblog.com/ I /322919/201405/181119499372608.png ",

"Http://images.cnitblog.com/ I /322919/201405/181120173901329.png ",

"Http://images.cnitblog.com/ I /322919/201405/181120244849561.png ",

"Http://images.cnitblog.com/ I /322919/201405/181120357812013.png ",

Http://images.cnitblog.com/ I /322919/201405/181120398596959.png"

};

ProgressBar = (ProgressBar) findViewById (R. id. progressBar );

ProgressBar. setMax (mUrl. length * 10 );

ProgressBar. setVisibility (View. VISIBLE );

// Asynchronous image download task

DownloadImageTask task = new DownloadImageTask (progressBar );

Task.exe cute (mUrl );

// Text File URL

String strUrl = "http://www.sogou.com/docs/about.htm ";

 

// Asynchronous download of Text File Content task

New downloadtexttask(cmd.exe cute (strUrl );

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.