以下摘自官网
class BitmapWorkerTask extends AsyncTask {
private final WeakReference imageViewReference; //注意用了final
private int data = 0;
public BitmapWorkerTask(ImageView imageView) {
// 使用WeakReference确保ImageView能被回收
imageViewReference = new WeakReference(imageView);
}
// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
}
// 完成后,看ImageView是否仍还在,在UI中更新.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
以下为本人项目中的代码片段,完整代码
//用静态内部类来防止持有外部类的隐性引用
static class WeakReferenceHander extends Handler {
//把Acitivity用WeakReference管理起来
private final WeakReference<ShareUploadActivity> mActivity;
public WeakReferenceHander(ShareUploadActivity activity) {
mActivity = new WeakReference<ShareUploadActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
if (mActivity.get() != null) {
mActivity.get().handleReceiveMessage(msg);
}
}
}
如果不用这种方式,请考虑,若一个子线程执行一个较耗时操作(运行未结束),此时UI线程finish()掉,但是GC无法对其回收,因为存在Handler的引用。
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u012951554/article/details/48055939