Android outofmemory错误分配

时间:2012-02-28 03:30:32

标签: android object garbage-collection bytearray out-of-memory

我一直在玩Androids示例代码蓝牙聊天。我正在考虑使用它作为我自己的应用程序的基础,但我一直在遇到内存错误。现在我把它设置为以非常快的速度从蓝牙设备读取大量数据。应用程序将它接收的字节数组更改为String但过了一会儿我得到了outofmemory错误。在删除它创建的所有String对象时,gc是否太慢?如何释放字符串

的内存

Bluetooth Chat

private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case MESSAGE_STATE_CHANGE:
            if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
            switch (msg.arg1) {
            case BluetoothChatService.STATE_CONNECTED:
                setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
                mConversationArrayAdapter.clear();
                break;
            case BluetoothChatService.STATE_CONNECTING:
                setStatus(R.string.title_connecting);
                break;
            case BluetoothChatService.STATE_LISTEN:
            case BluetoothChatService.STATE_NONE:
                setStatus(R.string.title_not_connected);
                break;
            }
            break;
        case MESSAGE_WRITE:
            byte[] writeBuf = (byte[]) msg.obj;
            // construct a string from the buffer
            String writeMessage = new String(writeBuf);
            mConversationArrayAdapter.add("Me:  " + writeMessage);
            break;
        case MESSAGE_READ:
            byte[] readBuf = (byte[]) msg.obj;
            // construct a string from the valid bytes in the buffer
            String readMessage = new String(readBuf, 0, msg.arg1);
            mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
            break;
        case MESSAGE_DEVICE_NAME:
            // save the connected device's name
            mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
            Toast.makeText(getApplicationContext(), "Connected to "
                           + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
            break;
        case MESSAGE_TOAST:
            Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                           Toast.LENGTH_SHORT).show();
            break;
        }
    }
};

MESSAGE_READ案例是运行数吨次的案例。我也将String转换为Hex字符串。有没有办法将byte []直接更改为可以节省宝贵内存的十六进制字符串?

1 个答案:

答案 0 :(得分:0)

关于内存不足的错误:我没有完美的解决方案,但在上次使用后使变量无效可能有助于GC加速其过程。

关于byte []到一个十六进制字符串,您可以尝试迭代字节数组并在每个字节上调用Integer.toHexString(...)