Android如何在App内存保持稳定的情况下泄漏内存
Android 会耗尽内存并重新启动应用程序,尽管运行时报告其正在使用的内存量几乎保持不变。
当应用程序使用的内存量几乎保持不变时,Android 手机怎么会出现内存不足的情况呢?
以下代码行返回 4 到 5 MB 之间的几乎恒定值,但 Android 的应用程序管理器显示正在运行的应用程序每次迭代泄漏约 1 MB,一段时间后,Android 由于内存不足而开始关闭进程。
(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())
当我使用 Eclipse 的内存分析器工具查看 HPROF 或在 Android 的堆工具中查看堆时,我看到了类似的结果。我也没有看到 Android 的分配跟踪器中分配了大块内存。
所以,对我来说最大的问题是: 1)应用程序中报告的内存和android报告的内存如何不同步? 2)我将给予我充分的信任,让我克服测试代码中的内存泄漏问题。 (我很高兴提供完整的测试代码。)
//This is an excerpt from the case.
import es.vocali.util.AESCrypt;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
...
byte[] data = getData(ONE_MEGABYTE);
AESCrypt aesCrypt = new AESCrypt(PASSWORD);
ByteArrayOutputStream baos = new ByteArrayOutputStream(ONE_MEGABYTE+ONE_KILOBYTE);
//Each iteration leaks approximately ONE_MEGABYTE
for(int i = 0; i < NUMBER_OF_ENCRYPTIONS; i++) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
aesCrypt.encrypt(2, bais, baos);
bais.close();
bais = null;
baos.reset();
}
Android runs out of memory and restarts applications even though the amount of memory that Runtime reports that it is using remains nearly constant.
How can an Android phone run out of memory when the amount of memory that it's applications use remains nearly constant?
The following line of code returns a nearly constant value between 4 and 5 MB, but Android's App Manager shows that the running app is leaking about 1 megabyte per iteration and after a while, Android starts shutting down process because memory is low.
(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())
I see similar results when I use Eclipse's Memory Analyzer Tool to view HPROF or in Android's Heap tool to view the heap. I didn't see a huge block of memory being allocated in Android's Allocation Tracker either.
So, the big questions for me are:
1) How can the memory as reported in an app and the memory as reported by android be out of synch?
2) I'll give full credit for pointers that get me past this memory leak in the test code. (I'm happy to provide the full test code.)
//This is an excerpt from the case.
import es.vocali.util.AESCrypt;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
...
byte[] data = getData(ONE_MEGABYTE);
AESCrypt aesCrypt = new AESCrypt(PASSWORD);
ByteArrayOutputStream baos = new ByteArrayOutputStream(ONE_MEGABYTE+ONE_KILOBYTE);
//Each iteration leaks approximately ONE_MEGABYTE
for(int i = 0; i < NUMBER_OF_ENCRYPTIONS; i++) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
aesCrypt.encrypt(2, bais, baos);
bais.close();
bais = null;
baos.reset();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论