android - 堆内存不足android

标签 android heap-memory

我有一个简单的 java 程序,它依赖于输入流。我必须读取一个 160 MB 的 ecg 文件,它在普通的 jvm 上运行完美,但是当我在 android 中运行这段代码时,它根本无法分配那 160 MB 并关闭我的应用程序。

这里是截取的代码:

//      reads the ecg file into a stream and stores it in the InputArray
    public byte[] readStream() throws IOException{
        FileInputStream inputFile = new FileInputStream(getDataPath());
        setBytesToSkip(0);
        inputFile.skip(getBytesToSkip());
        setLengthOfInputFile(inputFile.available());
        byte[] InputArray = new byte[getLengthOfInputFile()];
        setInputArray(InputArray);
        inputFile.read(getInputArray());
        inputFile.close();
        return inputArray;

    }
//              writes the bytes of the inputArray into a buffer bb
            public ByteBuffer bufferStream(byte[] array){
        inputArray = array;
        setBufferOffset(0);
        setBufferByteReadLength(getLengthOfInputFile());

        ByteBuffer bb = ByteBuffer.allocateDirect(getBufferByteReadLength());
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.put(getInputArray(), getBufferOffset(), getBufferByteReadLength());
        return bb;
    }

我也尝试过使用 DirectBuffer 来超越正常的堆,但仍然出现内存不足错误,例如:

dalvikvm-heap  PID:1715  Out of memory on a 167230992-byte allocation

有什么方法可以更有效地处理输入流的数据吗?或者我可以将一些存储
例如 sdcard 作为“堆”吗?

最好的问候洛雷佐

最佳答案

一般来说这是错误的做法。这些设备没有那么多内存可用于应用程序,如果有,您需要记住您需要与手机上运行的所有其他应用程序共享该内存。但是,这里有一些我立即注意到的事情。

首先,您正在尝试分配两次 160MB!

来到这里:

byte[] InputArray = new byte[getLengthOfInputFile()];

这里又是:

ByteBuffer bb = ByteBuffer.allocateDirect(getBufferByteReadLength());

您可以尝试重新安排这段代码,这样您就不会分配两次内存。

您还需要在 list 中设置 android:largeHeap="true"

关于android - 堆内存不足android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19875960/

相关文章:

java - 在回调 rxjava 中返回 Observable

android - 在 Eclipse 中的 Android 平板电脑模拟器上出现 "No Target Selected"错误

android - 聊天应用中的 Firebase 实时数据库结构

Java Web Start (JWS) 内存管理在 32 位和 64 位中似乎有所不同

java - G1GC 带有初始标记的长停顿

c - 在堆中释放一个内存块

android - 无法访问 Horizo​​ntalGridView 和 RecyclerView

android - 手动将 Cordova (Phonegap) 插件添加到现有的 android 项目

visual-studio - Visual Studio - 如何找到堆损坏错误的来源

c++ - 函数返回后如何删除堆分配的变量