Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 多執行緒下載遠程圖片

編輯:初階開發

在很多應用場景中,我們需要在 Android 設備上從遠程服務器下載圖片並顯示。這裡整理出兩種較為可靠的實現方法,供大家參考。

方法一:使用 Android 提供的 Http 類訪問遠程服務器

其中 AndroidHttpClient 是 SDK 2.2 新增的方法(API Level 8),使用時需注意版本問題。靜態訪問可直接調用;若 SDK 版本較低,則可考慮 Apache 的 Http 庫,或使用 HttpURLConnection、URLConnection。

  static Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("android123");
    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("android123Debug", "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 為遠程文件地址,第二個參數為 ImageView 對象,可直接讓其顯示下載的圖片。

  public class ImageDownloader {
    public void download(String url, ImageView imageView) {
      BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
      task.execute(url);
    }
  }

考慮到圖片可能較大,為給 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對象
      }
    }
  }
}

這兩種方法各有千秋:前者更貼近底層、控制更細,後者則調用簡潔、易於維護。根據實際項目的 SDK 版本與複雜度靈活選用即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved