使用蓝牙RFCOMM连接多个设备并在它们之间传输数据,以INSECURE方式使用RFCOMM插槽,所以在连接之前我不需要配对。
问题是,我得到一个设备列表,用于连接每个设备的线程,连接后发送一个字符串数据,它连接但数据传输不会一直发生。
对于连接,我需要使用UUID,UUID应该在所有设备上都是通用的,我每次运行时都需要更改它。
我使用了与谷歌蓝牙聊天相同的代码example
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothDataService.STATE_CONNECTED:
sen(); //After connecting am sending messaage
break;
case BluetoothDataService.STATE_CONNECTING:
showToast("connecting");
break;
case BluetoothDataService.STATE_LISTEN:
showToast("Listenining");
break;
case BluetoothDataService.STATE_NONE:
//setStatus(R.string.title_not_connected);
showToast("not connected");
break;
}
break;
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
tv2.setText(readMessage); //getting the message from sender and printing it in textview.
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
String mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
showToast("connected to -"+mConnectedDeviceName);
sen();
if(flag) { // used handler for connecting next deivces in the list of devices
handler.postDelayed(new Runnable() {
@Override
public void run() {
val++;
Log.e("type++",String.valueOf(val));
// mBlueDataService.stop();
}
}, 5000);
}
if(flag && temp>1) {
nextDevice.postDelayed(new Runnable() {
@Override
public void run() {
// mBlueDataService.start();
if (val <= (temp - 1)) {
Log.e("type", "" + String.valueOf(val) + "--" + String.valueOf(temp)+"---"+mDeviceList.size());
try {
connectDevice(mDeviceList.get(val));
} catch (Exception e) {
Log.e("type=",e.getStackTrace().toString());
e.printStackTrace();
}
}
}
}, 7000);
}
break;
}
}
};
如果我只连接了两台设备,它就会连接并发送和 第一次完美地接收数据,如果我再次运行它 不起作用。
我使用了来自Google蓝牙聊天example
的相同服务类