首页 > 解决方案 > 在 Android 中使用字节数组和位图时如何避免 OOM

问题描述

我正在制作一个可以发送图像和文本的简单 Android 聊天应用程序。我暂时在 localhost 中使用 MySQL 数据库,在其中存储图像的 base64 字符串(我需要这样做,因为我也必须在聊天的 web 版本中显示图像)。到目前为止,网络版本运行良好,但我的 Android 应用程序每发送 2-3 张图片就会遇到 OOM。

这是我将 base64 转换为位图并使用 Glide 显示的代码,我将其放入 RecyclerView 适配器以显示聊天中发送的图像:

byte[] decodedString = Base64.decode(c.getMessage(), Base64.DEFAULT);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize=16;
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
Glide.with(viewHolder.mymessageImage.getContext())
                        .asBitmap()
                        .load(decodedString)
                        .thumbnail(0.5f)
                        .into(viewHolder.mymessageImage);
decodedString=null;

这些是我得到的错误:

E/dalvikvm-heap: Out of memory on a 4205580-byte allocation.
E/GlideExecutor: Request threw uncaught throwable java.lang.OutOfMemoryError

我正在使用 Glide,因为以前,我使用

viewHolder.mymessageImage.setImageBitmap(decodedByte);

显示图像,它也导致OOM。我直接setImageBitmap时的错误是OOM

byte[] decodedString = Base64.decode(c.getMessage(), Base64.DEFAULT);

线。谷歌搜索后,很多人说 Glide 将是解决方案。Glide 确实有助于提高加载速度,但在发送 2-3 张图片并上下滚动 RecyclerView 几次后,它仍然会因 OOM 崩溃。

我试图解决这个问题一个星期无济于事。想着这件事,我正在拔头发。请帮我找到一个解决方案,让我的应用程序在没有 OOM 的情况下顺利运行。

标签: javaandroidandroid-glide

解决方案


推荐阅读