Android 为什么他们要检查WeakReference是否为null?

Android 为什么他们要检查WeakReference是否为null?,android,multithreading,image,android-asynctask,weak-references,Android,Multithreading,Image,Android Asynctask,Weak References,以下是android开发者关于如何异步下载图像的博文: 其中的代码片段: class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> { private String url; private final WeakReference<ImageView> imageViewReference; public BitmapDownloaderTask(ImageView i

以下是android开发者关于如何异步下载图像的博文:

其中的代码片段:

class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
    private String url;
    private final WeakReference<ImageView> imageViewReference;

    public BitmapDownloaderTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params) {
         // params comes from the execute() call: params[0] is the url.
         return downloadBitmap(params[0]);
    }

    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}
类BitmapDownloaderTask扩展异步任务{
私有字符串url;
私有最终WeakReference imageViewReference;
公共位图下载任务(ImageView ImageView){
imageViewReference=新的WeakReference(imageView);
}
@凌驾
//实际下载方法,在任务线程中运行
受保护位图doInBackground(字符串…参数){
//params来自execute()调用:params[0]是url。
返回下载位图(参数[0]);
}
@凌驾
//下载图像后,将其与imageView关联
受保护的void onPostExecute(位图){
如果(isCancelled()){
位图=空;
}
if(imageViewReference!=null){
ImageView=imageViewReference.get();
如果(imageView!=null){
设置图像位图(位图);
}
}
}
}
问题:
为什么他们要检查imageViewReference是否为空?那是拼错的吗

看起来像是非常陈旧的代码。去掉这张支票,就不会有什么不好的事情发生。

我看不出有什么好的理由。您可以安全地删除它。WeakReference可以很容易地删除GC@njzk2是正确的-它甚至被声明为final,因此必须在初始值设定项或构造函数中赋值-否则它甚至无法编译-并且不允许任何内容更改其赋值,因此它不能为null。@blackbelt:WR中的ref可以GCed,因此需要测试WR.get返回的值,但是WR对象本身与任何对象一样,它不能像那样消失。