Android開發之異步獲取並下載網絡資源-下載圖片和下載文本內容

在android網絡開發過程當中,常常須要獲取網絡資源,好比下載圖片,下載文本文件內容等,這個時候就須要http請求來獲取相應的網絡資源。首先看看實例效果圖:android

 

            

                                  下載圖片截圖                                                                                                下載文本文件內容截圖網絡

下面介紹如何來實現這樣的開發:異步

(1)從指定的URL獲取對應的流ide

既然要獲取網絡資源,那麼首先得有個URL,那麼這裏我首先封裝一個打開URL鏈接獲取到的InputStream 流,這樣一來不管是圖片資源仍是文本文件資源均可以使用該接口方法來獲取流。測試

該功能主要應用URLConnection和HttpURLConnection來實現,具體實現方案以下:this

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;
        
    }

(2)封裝了上面的獲取流方法接口後,咱們就能夠利用上面封裝的方法來獲取並下載相應圖片和文本文件內容了url

獲取並下載圖片資源方法:spa

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;
    }

(3)在獲取下載圖片資源和文本內容資源方法都完成後,如今就能夠開始下載任務了,爲了防止等待效應,通常採用異步任務來下載網絡資源。htm

對對應的下載資源任務封裝各自的異步下載任務便可。下面就是實現異步下載任務的方案:

異步下載圖片任務:

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 = "下載完成!一共下載了"+imagesCount +"張圖片";
            Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();
        }
        
    }

 

異步下載文本文件內容任務:

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]);
        }
        
    }

這樣一來,異步下載網絡資源就完成了。

下面爲了讀者方便測試,下面提供本文實例代碼中的相關網絡資源URL,以方便你們本身測試使用。其他非核心代碼就不在貼出來,望讀者見諒。

//圖片下載URLs
private
String[] mUrl = { "https://images0.cnblogs.com/i/322919/201405/181111308592436.png", "https://images0.cnblogs.com/i/322919/201405/181111385003770.png", "https://images0.cnblogs.com/i/322919/201405/181111493901865.png", "https://images0.cnblogs.com/i/322919/201405/181111550463327.png", "https://images0.cnblogs.com/i/322919/201405/181117587961455.png", "https://images0.cnblogs.com/i/322919/201405/181118041251414.png", "https://images0.cnblogs.com/i/322919/201405/181119313754936.png", "https://images0.cnblogs.com/i/322919/201405/181119357816682.png", "https://images0.cnblogs.com/i/322919/201405/181119458753432.png", "https://images0.cnblogs.com/i/322919/201405/181119499372608.png", "https://images0.cnblogs.com/i/322919/201405/181120173901329.png", "https://images0.cnblogs.com/i/322919/201405/181120244849561.png", "https://images0.cnblogs.com/i/322919/201405/181120357812013.png", "https://images0.cnblogs.com/i/322919/201405/181120398596959.png" }; progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar.setMax(mUrl.length*10); progressBar.setVisibility(View.VISIBLE); //異步下載圖片任務
DownloadImageTask task
= new DownloadImageTask(progressBar); task.execute(mUrl); //文本文件URL String strUrl = "http://www.sogou.com/docs/about.htm";
//異步下載文本文件內容任務
new DownloadTextTask().execute(strUrl);
相關文章
相關標籤/搜索