【问题标题】:Send long text message on android via Bluetooth通过蓝牙在android上发送长短信
【发布时间】:2011-07-11 12:23:26
【问题描述】:

我正在使用来自 android 的示例应用程序:BluetoothChat。 但是,当我尝试发送大于 1024 字节的字符串时,消息不会传输。 我尝试更改下面的代码以发送超过 1024 个字节,但我没有成功。 请帮帮我。

阅读代码:

public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[1024];
            int bytes;

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);

                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(SmallWorld.MESSAGE_READ, bytes, -1,
                            buffer).sendToTarget();

                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
        }

发送代码:

public void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);

            // Share the sent message back to the UI Activity
            mHandler
                    .obtainMessage(SmallWorld.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

打电话来写:

    String message="blabla";
byte[] send = message.getBytes();
        mChatService.write(send);

【问题讨论】:

  • 您收到的错误信息是什么?
  • 我没有收到错误消息,它只发送 1024 字节的字符串(它切断了字符串),即使我改变了缓冲区的大小。
  • 发送字符串的代码在哪里
  • 你怎么叫写?确保传递给写入的缓冲区不限于 1024。

标签: android bluetooth


【解决方案1】:

在写入之后,您可能希望刷新流以强制发送数据,因为可能是流正在缓冲数据并在实际发送数据之前等待更多。 试试..

mmOutStream.write(buffer);
mmOutStream.flush();

【讨论】:

  • 谢谢,我明天去看看。
  • 它工作了,但现在我有一个新问题。数组的最大大小是多少:new byte[1024];我遇到内存泄漏
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多