为什么我们在加载位图时使用WeakReference而不是SoftReference

时间:2015-04-10 06:42:44

标签: android bitmap

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private int data = 0;

    public BitmapWorkerTask(ImageView imageView) {
        // Use a WeakReference to ensure the ImageView can be garbage collected
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        data = params[0];
        return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
    }

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}

我想当执行doInBackground时,GC可能会杀死imageViewReference。这会导致无法加载位图。为什么不使用SoftReference?

应尽快清除并排入SoftReference,即万一VM存在内存不足的危险。

似乎SoftReference更安全。

0 个答案:

没有答案