http://blog.csdn.net/longlong3050/article/details/6709528
修改後的代碼
import java.io.InputStream; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import android.widget.ImageView; /** * @類名:ImageDownloader * @功能描述:優化的ImageDownloader, 不帶緩存,在線下載,用戶頭像請使用。 * @作者: William Xu * @創建日期:2013-6-7 * @修改人: * @修改日期: * @修改備註: * @版本號:1.0 */ public class ImageDownloader { public void download(String url, ImageView p_w_picpathView) { BitmapDownloaderTask task = new BitmapDownloaderTask(p_w_picpathView); task.execute(url); } class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> { private final WeakReference<ImageView> p_w_picpathViewReference; // 使用WeakReference解決內存問題 public BitmapDownloaderTask(ImageView p_w_picpathView) { p_w_picpathViewReference = new WeakReference<ImageView>(p_w_picpathView); } @Override protected Bitmap doInString... params) { // 實際的下載線程,內部其實是concurrent線程,所以不會阻塞 Bitmap bitmap = null; try { URL p_w_picpathUrl = new URL(params[0]); HttpURLConnection conn = (HttpURLConnection) p_w_picpathUrl .openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); } catch (Exception ex) { Log.e("", "getBitmap catch Exception...\nmessage = " + ex.getMessage()); } return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { // 下載完後執行的 if (isCancelled()) { bitmap = null; } if (p_w_picpathViewReference != null) { ImageView p_w_picpathView = p_w_picpathViewReference.get(); if (p_w_picpathView != null && bitmap != null) { p_w_picpathView.setImageBitmap(bitmap); // 下載完設置p_w_picpathview爲剛纔下載的bitmap對象 } } } } }