Android development-obtain and download network resources asynchronously-download images and text content

Source: Internet
Author: User

Android development-obtain and download network resources asynchronously-download images and text content
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 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 the 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. getInputS Tream () ;}} catch (Exception ex) {Log. v ("Networking", ex. getLocalizedMessage (); throw new IOException ("Error connecting");} return in;} after the code is copied (2, we can use the encapsulated method above to obtain and download the corresponding image and text file content to obtain and download the image resource method: 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 (IOEx Ception e) {// TODO Auto-generated catch block Log. v ("NetworkingActivity", e. getLocalizedMessage ();} return bitmap;} copy the code to obtain and download the text content. Method: copy the 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 InputStream Reader (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 ). After the source method is complete, you can download the 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 is a scheme for asynchronous download tasks: asynchronous download image tasks: copy the 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) images Count * 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 "; Toast. makeText (getBaseContext (), str, Toast. LENGTH_SHORT ). show () ;}} copy the code to asynchronously download the text file content task: copy the 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 to complete asynchronous download of network resources. 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 // image download URLsprivate 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"}; 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.exe cute (mUrl); // text file URLString 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.