2012-02-28 69 views
1

我一直在玩Android的示例代碼藍牙聊天。我正在考慮將它用作我自己的應用程序的基礎,但我一直遇到內存不足的錯誤。現在我已經設置了以相當快的速度從藍牙設備讀取大量數據。該應用程序將它收到的字節數組更改爲一個字符串,但過了一段時間後,我得到了內存異常錯誤。刪除創建的所有String對象時gc是否太慢?如何釋放字符串Android outofmemory錯誤分配

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案件的內存是運行噸倍一體。此外,我將字符串轉換爲十六進制字符串。有沒有辦法將字節[]直接更改爲可以節省寶貴內存的十六進制字符串?

回答

0

關於內存不足錯誤:我還沒有完美的解決方案,但在最後一次使用後取消變量可能有助於GC加速其過程。

關於以不吉利的東西的字符串的byte [],您可以嘗試遍歷字節數組,每個字節調用Integer.toHexString(...)