java - 在 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 的情况下顺利运行。
解决方案
推荐阅读
- ansible - ansible with_items 用逗号分隔 item.values
- if-statement - 在 Google 表格上查找最常出现的条件
- javascript - 如何在 jquery 中单击元素
- javascript - Symfony 2 - 使用 FormData 和 ajax 上传文件,请求中没有任何内容
- c++ - std::byte 指针是否应该用于指针算术?
- javascript - 如何在 JavaScript 严格模式下使用 fetch() API?
- microsoft-graph-api - Microsoft Graph Beta getSchedule API 不一致主题
- c# - 并行 For 循环 Selenium C# - 不是测试
- c# - 使用合成从 UWP 中的 UI 控件创建视频
- python - 在 Rstudio 中集成 python 的关键难点是什么?