我一直在按照这个 Android 指南进行蓝牙通信。
为了确切地解释我的目标,当两个设备配对成功时,每个设备上都会打开两个不同的活动(服务器和客户端),在服务器活动上有不同的按钮,在客户端活动上只有一个文本视图。 我想能够在服务器设备上按下一个按钮并在客户端上显示它。
我已经成功建立了两个设备之间的连接,但现在我想发送数据,但我还没有成功。
他们提供了以下代码用于数据传输:
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是什么或它的作用。
除了错误之外,我甚至不知道应该把这段代码放在哪里。它应该放在我打开的第二个活动(服务器和客户端)中还是主要活动中?如果放在Server活动中,它应该在所有按钮的onClick方法中,每个按钮发送不同的字节码?在这段代码中,我们如何区分谁是发送方,谁是接收方?
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
- addy123<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
或者<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
。 - ban-geoengineering