图片下载,点击返回崩溃

142 阅读1分钟

在适配android 11过程中,发现一个问题,app 进入一个activity(如查看大图,或者查看证书),点击下载图片,然后点击返回退出该activity,直接导致app崩溃 IllegalArgumentException: You cannot start a load for a destroyed activity 通过百度,自我排查,主要涉及到的是下面两部分代码

Glide.with(mContext).asBitmap().load(url)
        .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                boolean isSave = save(mContext, resource);
                if (isSave){
                    Toast.makeText(mContext, "已保存至相册", Toast.LENGTH_SHORT).show();
                }
            }
        });
 File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File destFile = new File(picDir, context.getPackageName() + File.separator + System.currentTimeMillis() + ".jpg");
//            FileUtils.copy(imageFile, destFile.getAbsolutePath());
        OutputStream os = null;
        boolean result = false;
        try {
            if (!destFile.exists()) {
                destFile.getParentFile().mkdirs();
                destFile.createNewFile();
            }
            os = new BufferedOutputStream(new FileOutputStream(destFile));
            result = bitmap.compress(Bitmap.CompressFormat.JPEG, 50, os);
            if (!bitmap.isRecycled()) bitmap.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        MediaScannerConnection.scanFile(
                context,
                new String[]{destFile.getAbsolutePath()},
                new String[]{"image/*"},
                (path, uri) -> {
                    Log.d(TAG, "saveImgToAlbum: " + path + " " + uri);
                    // Scan Completed
                });
        return result;

主要原因是大概是,我们通过glide 生成bitmap 然后再将这个bitmap保存到本地的过程中,退出activity,触发了glide的生命周期,onResourceReady 回调中产生的Btimap resource 就出现了问题

处理方式就是用一个变量去接收这个resource 的copy

public static Bitmap copyBitmap(Bitmap source) {
    return source.copy(source.getConfig(), true);
}

然后在合适的时候把这个copy 的bitmap 给回收掉就可以了