Alan Moment
  • Introduction
  • 智慧家庭
    • Fibaro 系統整合便宜的 IP Cam
  • Life
    • 用AWS Glacier做最後的冷資料備份
    • 如何在macOS修改影音檔日期
  • 3D Printer
    • Atom2.5EX 之血淚組裝
    • 列印經驗紀錄
      • SpoolHolder
    • 製圖經驗
      • Turntable
      • 重製Atom3散熱風扇
    • 線材經驗
      • PETG
        • 首測
  • Kubernetes
    • 使用Kops建立Kubernetes
    • 使用HelmV2
    • Kubernetes的技術問題排解技巧
  • PHP
    • 管理PHP Library的利器Composer
    • PHP安裝JSON
    • Phalcon首發
    • Gearman Job Worker for PHP
    • Laravel 首發 !!!
    • Data Encrypt & Decrypt
  • Python
    • Django + Python 開發環境建置
  • Android
    • Android zipcode library of maven
    • Android use foreign object of OrmLite
    • ProgressBar while loading ListView of Android
    • AsyncTask download image by the Android
    • Use Thread control Android UI
    • Android Universal Image Loader
  • Ruby on Rails
    • Install rmagick on the Windows of Ruby on Rails
    • Ruby on Rails deploy on Heroku
    • Ruby on Rails 小問題
  • React
    • Ditched AngularJS for React
  • Tessel
    • 很潮的 Tessel
    • Connect to Slack on Tessel
    • Baby Help on Tessel
  • Node.js
    • CentOS 安装 Node.js 0.8.5
  • OOAD
    • Injection Principle Design Pattern
  • Linux
    • SSH免密碼登入遠端電腦
    • Apache與Tomcat的結合
    • The bash auto build
  • Hadoop
    • CentOS 5.5 + Hadoop 0.20
    • CentOS 5.5 + Hbase 0.94.8
    • Hadoop + Hbase 叢集環境
    • Hadoop 溝通橋梁之 Thrift 0.7
    • 使用MapReduce之替代方案Hive
    • 使用Sqoop將MySQL資料匯入Hbase
  • Database
    • 吃足苦頭的Mssql
  • IDE
    • Netbeans console中文亂碼解決方法
    • 用NetBeans開發Ruby On Rails
  • Agile
    • 淺談我的Agile
  • 協作工具
    • 建置專屬自己的Github之Gitlab
    • Gitlab 4.1 upgrade to Gitlab 6.0超偷懶方法
    • Install Phabricator and run on the Gitlab
    • Phabricator 基本應用
    • Phabricator review code應用
    • Redmine之基本建置與Scrum應用
    • Omnibus Gitlab 7 基礎操作
    • Git Push Notify to Slack on Gitlab
    • phabricator-extensions-Sprint 無法抓到正確的 Story Points
  • 其他
    • 慶祝Octopress開張
    • 走在時尚的尖端! Ghost
    • 大搬家
    • 網頁教學初體驗
    • 網路攻擊很猖狂
Powered by GitBook
On this page

Was this helpful?

  1. Android

AsyncTask download image by the Android

PreviousProgressBar while loading ListView of AndroidNextUse Thread control Android UI

Last updated 3 years ago

Was this helpful?

開發Android時常需要呈現圖片,但不可能圖片都是從Drawable中撈出來,一定有時需要從ImageServer或是透過網址取得圖片。

若是用一般的方式解決

try {
  URL url = new URL(imageUrl);
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setDoInput(true);
  connection.connect();
  InputStream input = connection.getInputStream();
  Bitmap bitmap = BitmapFactory.decodeStrea (input);
  return bitmap;
} catch (IOException e) {
  e.printStackTrace();
  return null;
}

這樣子會造成讀取完圖片才會往下繼續執行的窘境,如果Timeout那畫面會停留更久。所以要用的特性來實作這個功能。

Android 4.0之後為了避免跟網路溝通時造成畫面停滯的問題,在與網路溝通的程式碼中必須要用執行緒的方式來進行與網路的溝通。

建立ImageDownloadTask

先在AndroidManifest.xml開啟網路權限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

為了避免在短時間內下載重複的圖片,所以用url當作key做了cache的機制imageCache.put(params[0], mIcon11),只要cache中不超過空間限制,都不會重複向遠端撈取圖片。

package com.example.test;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.URLConnection;

/**
* 遠端下載圖片
*
* @author Alan
* @since 2013/10/05
*/
public class ImageDownloadTask extends AsyncTask<string void bitmap> {
  private static final String LOG_TAG = ImageDownloadTask.class.getName();
  private ImageView bmImage;
  private static LruCache imageCache;
  private static final int CACHE_SIZE = 1; //1MB

  public ImageDownloadTask(ImageView bmImage) {
    this.bmImage = bmImage;

    // 設定圖片快取
    if (imageCache == null) {
      imageCache = new LruCache(CACHE_SIZE * 1024 * 1024);
    }
  }

  protected Bitmap doInBackground(String... params) {
    if (imageCache.get(params[0]) == null) {
      android.graphics.Bitmap mIcon11 = null;
      URLConnection urlConnection = null;
      InputStream in = null;
      try {
        urlConnection = new java.net.URL(params[0]).openConnection();
        urlConnection.setConnectTimeout(3 * 1000);
        urlConnection.setReadTimeout(10 * 1000);
        in = urlConnection.getInputStream();
        mIcon11 = BitmapFactory.decodeStream(in);

        // 記錄已下載圖片的快取
        imageCache.put(params[0], mIcon11);
        in.close();
      } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
        e.printStackTrace();
      }

      return mIcon11;
    } else {
      return (Bitmap) imageCache.get(params[0]);
    }
  }

  protected void onPostExecute(android.graphics.Bitmap result) {
    super.onPreExecute();

    // 設定圖片物件
    bmImage.setImageBitmap(result);
    this.bmImage = null;
  }
}

用起來很簡單

ImageView iv = new ImageView(this);
ImageDownloadTask imageDownloadTask = new ImageDownloadTask(iv);
imageDownloadTask.execute(imageUrl);

Oct 18th, 2013 12:22:00am

AsyncTask