1.定义handler
private static final int DOWNLOAD_IMAGE_SUCCESS = 0;
private static final int DOWNLOAD_IMAGE_FAILURE = 1;
private ImageView mDetailImageView;
private String mImageUrl;
private Thread mDownloadImageThread;
private Bitmap mDownloadImageBitmap;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case DOWNLOAD_IMAGE_SUCCESS:{
if (mDownloadImageBitmap != null) {
mDetailImageView.setImageBitmap(mDownloadImageBitmap);
mDetailImageView.setVisibility(View.VISIBLE);
}
break;
}
case DOWNLOAD_IMAGE_FAILURE:{
if (mDownloadImageBitmap != null) {
mDownloadImageBitmap.recycle();
mDownloadImageBitmap = null;
// TODO: should set default image to notice user download failure.
mDetailImageView.setVisibility(View.VISIBLE);
}
break;
}
}
}
};
2.定义runnable
private class DownloadImageRunner implements Runnable {
public void run() {
Message msg = new Message();
msg.what = DOWNLOAD_IMAGE_SUCCESS;
try {
URL url;
url = new URL(mImageUrl);
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6000);
conn.setDoInput(true);
conn.setUseCaches(false);
InputStream is = conn.getInputStream();
mDownloadImageBitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
msg.what = DOWNLOAD_IMAGE_FAILURE;
e.printStackTrace();
} catch (Exception e) {
msg.what = DOWNLOAD_IMAGE_FAILURE;
e.printStackTrace();
}
mHandler.sendMessage(msg);
}
}
3.使用线程
DownloadImageRunner downloadImageRunner = new DownloadImageRunner();
mDownloadImageThread = new Thread(downloadImageRunner); mDownloadImageThread.start();
4.Activity销毁时清理内存
@Override
public void onDestroy() {
super.onDestroy();
if (mDownloadImageBitmap != null) {
mDownloadImageBitmap.recycle();
mDownloadImageBitmap = null;
}
}