我一直在遵循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) { } } }
但是这行会产生错误
// Send the obtained bytes to the UI activity mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
并且在指南中没有解释。我不知道什么是mHandler或做什么。
除了错误之外,我什至都不真正知道将这些代码放在哪里。应该在我打开的第二个活动(服务器和客户端)中还是在主要活动中?如果在“服务器”活动中,是否应在onClick方法中为每个按钮发送不同字节代码的所有按钮?在这段代码中,我们如何区分谁在发送和谁在接收?
查看Google在SDK中提供的BluetoothChat示例。它将向您展示如何通过蓝牙实现基本的文本发送。