android 非同步擷取圖片

來源:互聯網
上載者:User

原文地址:

 http://bbs.chinaunix.net/thread-1926876-1-1.html

在某些時候我們需要在Android裝置上下載遠端伺服器上的圖片來進行顯示,這裡我整理出兩種比較好的方法來實現遠程圖片的下載。  方法一、直接通過Android官方提供的Http類訪來問遠程伺服器,這裡AndroidHttpClient是SDK 2.2中新出的方法,API Level為8,大家需要注意下,靜態訪問可以直接調用,如果SDK版本較低可以考慮Apache的Http庫,當然HttpURLConnection或URLConnection也可以。static Bitmap downloadBitmapByCwj(String url) {     final AndroidHttpClient client = AndroidHttpClient.newInstance("linux初學三月");     final HttpGet getRequest = new HttpGet(url);     try {         HttpResponse response = client.execute(getRequest);         final int statusCode = response.getStatusLine().getStatusCode();         if (statusCode != HttpStatus.SC_OK) {              Log.e("cwjDebug", "Error " + statusCode + " while retrieving bitmap from " + url);              return null;         }                  final HttpEntity entity = response.getEntity();         if (entity != null) {             InputStream inputStream = null;             try {                 inputStream = entity.getContent();                  final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);                 return bitmap;             } finally {                 if (inputStream != null) {                     inputStream.close();                   }                 entity.consumeContent();             }         }     } catch (Exception e) {           getRequest.abort();         Log.e("Debug", "Error while retrieving bitmap from " + url, e.toString());     } finally {         if (client != null) {             client.close();         }     }     return null; }複製代碼這裡提醒大家,BitmapFactory類的decodeStream方法在網路逾時或較慢的時候無法擷取完整的資料,這裡我們通過繼承FilterInputStream類的skip方法來強制實現flush流中的資料,主要原理就是檢查是否到檔案末端,告訴http類是否繼續。static class FlushedInputStream extends FilterInputStream {     public FlushedInputStream(InputStream inputStream) {         super(inputStream);     }     @Override     public long skip(long n) throws IOException {         long totalBytesSkipped = 0L;         while (totalBytesSkipped < n) {             long bytesSkipped = in.skip(n - totalBytesSkipped);             if (bytesSkipped == 0L) {                   int byte = read();                   if (byte < 0) {                       break;  // we reached EOF                   } else {                       bytesSkipped = 1; // we read one byte                   }            }             totalBytesSkipped += bytesSkipped;         }         return totalBytesSkipped;     } }複製代碼方法二、通過AsyncTask的非同步任務  從Android 1.5韌體開發平台開始Google提供了一個AsyncTask類來協助開發人員處理非同步下載的實現,相對於Thread線程而言他可以運行在UI線程中,其內部的實現是從Java 5開始的並發包concurrent中派生而來的,總體實現比較可靠就是資源佔用略大了些。不過使用起來比簡單。這裡下載圖片類ImageDownloader類的download方法可以很好的處理實現UI顯示等操作,參數一url為遠程server上檔案的url,第二個參數為imageview對象,可以直接讓imageview顯示出下載的遠程圖片。public class ImageDownloader {     public void download(String url, ImageView imageView) {             BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);             task.execute(url);         }     } }複製代碼有關具體的AsyncTask類實現,考慮到圖片可能較大,為了給JVM充分的空間儲存,這裡推薦大家使用弱引用來儲存ImageView對象。class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {     private String url;     private final WeakReference<ImageView> imageViewReference;  //使用WeakReference解決記憶體問題    public BitmapDownloaderTask(ImageView imageView) {         imageViewReference = new WeakReference<ImageView>(imageView);     }   @Override     protected Bitmap doInBackground(String... params) {   //實際的下載線程,內部其實是concurrent線程,所以不會阻塞            return downloadBitmap(params[0]);     }     @Override      protected void onPostExecute(Bitmap bitmap) {   //下載完後執行的        if (isCancelled()) {             bitmap = null;         }         if (imageViewReference != null) {             ImageView imageView = imageViewReference.get();             if (imageView != null) {                 imageView.setImageBitmap(bitmap);  //下載完設定imageview為剛才下載的bitmap對象            }         }     } }



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.