Android development asynchronously acquires and downloads network resources

Source: Internet
Author: User
Tags file url stub
1) Get the corresponding stream from the specified URL

  Since we need to obtain a network resource, we must first have a URL, so here I first encapsulate an InputStream stream obtained by opening a URL connection, so that whether it is a picture resource or a text file resource, this interface method can be used to obtain the stream. This function is mainly implemented by URLConnection and HttpURLConnection. The specific implementation scheme is as follows: 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.getLocalizedMessag e ()); throw new IOException ("Error connecting");} return in;} Copy the code 

(2) After encapsulating the above get stream method interface, we can use the above encapsulated method to obtain and download the corresponding image and The content of the text file is how to get and download the image resources: copy the 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;} 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 the code 

(3) The methods for obtaining the downloaded image resource and text content resource are completed After that, you can now start downloading tasks. To prevent waiting effects, asynchronous tasks are generally used to download network resources. It is sufficient to encapsulate the respective asynchronous download tasks for the corresponding download resource tasks. The following is the plan to implement the asynchronous download task: Asynchronous download image task: 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 completed! Downloaded a total of "+ imagesCount +" pictures "; Toast.makeText (getBaseContext (), str, Toast.LENGTH_SHORT) .show ();}} Copy code asynchronously download 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 the code so that asynchronous downloading of network resources is completed. For the convenience of the reader, the following is provided below Relevant web resource URLs in the example code for the convenience of everyone to test and use. The rest of the non-core code is not posted, I hope readers forgive me. Copy code // Image download URLs private String [] mUrl = {"181111308592436.png", "181111385003770.png", "181111493901865.png", "181111550463327.png", "181117587961455.png", "181118041251414.png", "181119313754936.png", "181119357816682 .png "," 181119458753432.png "," 181119499372608.png "," 181120173901329.png "," 181120244849561.png "," 181120357812013.png "," 181120398596959.png "}; progressBar = (ProgressBar) findViewById (R. id.progressBar); progressBar.setMax (mUrl.length * 10); progressBar.setVisibility (View.VISIBLE); // asynchronous download image task DownloadImageTask task = new DownloadImageTask (progressBar); task.execute (mUrl); // text File URL String strUrl = "http://www.sogou.com/docs/about.htm"; // Asynchronous download of text file content task new DownloadTextTask (). Execute (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.