通过蓝牙在Android上发送长文本信息

5

我正在使用 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);

你收到了什么错误信息? - Hassan Voyeau
我没有收到错误信息,它只发送了1024字节的字符串(它截断了字符串),即使我改变缓冲区的大小。 - Beno
发送字符串的代码在哪里? - Dennis Mathews
你是如何调用write函数的?请确保传递给write函数的缓冲区大小不仅仅限制在1024。 - Hassan Voyeau
1个回答

2

在写入数据后,您可能想要刷新流以强制发送数据,因为流可能会缓冲数据并等待更多数据才能实际发送数据。尝试..

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

谢谢,我明天会检查这个。 - Beno
它起作用了,但现在我有一个新问题。数组的最大大小是多少:new byte[1024]?我遇到了内存泄漏。 - Beno

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接