两个Android设备之间的蓝牙数据传输

Sim*_*ons 10 java android bluetooth transfer

我一直在关注此Android指南进行蓝牙通信

为了准确地解释我想要做什么,当两个设备配对时,在每个设备(服务器和客户端)上打开两个不同的活动,在服务器活动上我有不同的按钮,在客户端活动上只有一个textview.我希望能够按下服务器设备上的按钮并将其显示在客户端上.

我已经设法在两个设备之间建立连接,但现在我想发送我无法做的数据.

他们提供此代码用于数据传输:

private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the input and output streams, using temp objects because
    // member streams are final
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) { }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}

public void run() {
    byte[] buffer = new byte[1024];  // buffer store for the stream
    int bytes; // bytes returned from read()

    // Keep listening to the InputStream until an exception occurs
    while (true) {
        try {
            // Read from the InputStream
            bytes = mmInStream.read(buffer);
            // Send the obtained bytes to the UI activity
            mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
    try {
        mmOutStream.write(bytes);
    } catch (IOException e) { }
}

/* Call this from the main activity to shutdown the connection */
public void cancel() {
    try {
        mmSocket.close();
    } catch (IOException e) { }
}
}
Run Code Online (Sandbox Code Playgroud)

但是这一行会产生错误

// Send the obtained bytes to the UI activity
            mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
Run Code Online (Sandbox Code Playgroud)

并没有在指南中解释.我不知道mHandler是什么或做什么.

除了错误,我甚至不知道在哪里放这个代码.它应该在我打开还是在主要的第二个活动(服务器和客户端)中?如果在Server活动中,是否应该在onClick方法中为每个按钮发送不同字节代码的所有按钮?在此代码中,我们如何区分发送者和接收者?

Jor*_*esh 12

查看Google在SDK中提供的BluetoothChat示例.它将向您展示如何通过蓝牙实现基本的文本发送.