安卓图片视图导致应用程序变慢

3

我在我的应用程序中有一个ImageView。在添加这个ImageView之前,应用程序运行顺畅。现在它抛出ANR错误

图像以base64编码字符串的形式保存在数据库中,并使用以下方式解码为位图并加载到imageview中:

imageView.setImageBitmap(bitmap);

bitmap的转换和将其应用到ImageView中,所有这些操作都在一个AsyncTask中完成:

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

    public BitmapWorkerTask(ImageView imageView, String data) {
        imageViewReference = new WeakReference<ImageView>(imageView);
        this.data = data;
    }


    @Override
    protected Bitmap doInBackground(Integer... params) {

        byte[] decodedString = Base64.decode(data, Base64.DEFAULT);
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inPurgeable = true;
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length, options);

        return decodedByte;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}
AsyncTask是通过以下代码从主UI中调用的:
BitmapWorkerTask task = new BitmapWorkerTask(pollWebView,decodedStrings[1]);
                task.execute();

decodedStrings[1] 包含了base64编码的图片数据URL。

有没有解决这个问题的方法?


位图的尺寸是多少? - greenapps
它的大小可以从10 kb到10 mb不等。 - Jyothish
2个回答

3
主要问题是WeakReference,它使您的应用程序变慢,请删除它并尝试不使用它。
请勿使用此功能。
 private final WeakReference<ImageView> imageViewReference;

只需使用

private final ImageView imageViewReference;

那背后的原因是什么? - Jyothish
1
请查看这个链接,并接受答案,如果它有效的话。 - Ankit Khare
我只有9点声望,需要15点才能点赞。所以我做不到。对此感到抱歉。 - Jyothish

0
请使用以下代码压缩图像(75% 压缩):
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 75, baos);
        byte[] imageBytes = baos.toByteArray();
       String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接