我需要检查 AsyncTask 中的 WeakReference 吗?

Do I need to check a WeakReference inside an AsyncTask?

我正在使用从 Android 开发人员文档中获取的以下模式:

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);
            }
        }
    }
}

我的问题是:为什么我们需要在onPostExecute()的开头检查imageViewReference是否为null?因为它是在构造函数中分配的,所以此时不​​应该有任何方法让它为 null。我确实理解验证 get() 调用的 return 以验证基础 ImageView 是否仍然存在。谢谢。

不,您不应该为 null 检查 imageViewReference,您应该只检查 null 它涵盖的内容 - ImageView 使用 return get 方法的值。

约翰,你是对的,没有必要这样做。