Android開發之非同步擷取並下載網路資源

來源:互聯網
上載者:User

Android開發之非同步擷取並下載網路資源

  1)從指定的URL擷取對應的流

 

既然要擷取網路資源,那麼首先得有個URL,那麼這裡我首先封裝一個開啟URL串連擷取到的InputStream 流,這樣一來無論是圖片資源還是文字檔資源都可以使用該介面方法來擷取流。

 

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

 

複製代碼

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)封裝了上面的擷取流方法介面後,我們就可以利用上面封裝的方法來擷取並下載相應圖片和文字檔內容了

 

擷取並下載圖片資源方法:

 

複製代碼

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;

    }

複製代碼

 

 

擷取並下載常值內容方法:

 

複製代碼

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)在擷取下載圖片資源和常值內容資源方法都完成後,現在就可以開始下載任務了,為了防止等待效應,一般採用非同步任務來下載網路資源。

 

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

 

非同步下載圖片任務:

 

複製代碼

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 =

        {

            "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);

//非同步下載圖片任務

DownloadImageTask task = new DownloadImageTask(progressBar);

task.execute(mUrl);

//文字檔URL

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

 

//非同步下載文字檔內容任務

new DownloadTextTask().execute(strUrl);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.