如何让两台安卓设备在不取消配对的情况下连接到同一蓝牙设备



我有一个通过 SPP 与蓝牙设备通信的应用程序,我发现当我尝试使用另一台 Android 设备连接到同一蓝牙设备时,即使我关闭应用程序或断开蓝牙设备的电源,其他 Android 设备也无法连接到蓝牙设备。 唯一的解决方法是取消配对蓝牙设备。 我确定我已经关闭了所有插座并向我的蓝牙设备发送了正确的断开连接命令;我想知道为什么我的第二台 Android 设备无法连接到我的蓝牙设备,除非我取消配对。

以下是连接代码:

公共类 ConnectTask 扩展了 AsyncTask {

private final WeakReference<Context> weakContext;
BluetoothDevice mdevice;
BluetoothSocket mSocket;
ProgressDialog pd;
public ConnectTask(Context context) {
weakContext = new WeakReference<Context>(context);
}
@Override
protected void onPreExecute() {
final Context context = weakContext.get();
if (context != null) {
super.onPreExecute();
if (pd != null) {
pd = null;
}
pd = new ProgressDialog(context);
pd.setTitle("Connecting...");
pd.setCancelable(false);
if (!pd.isShowing()) {
pd.show();
}
}
BluetoothConnectionService.btAdapter.cancelDiscovery();
}
@Override
protected Void doInBackground(Void... params) {
try {
try {
Thread.sleep(1000);
mdevice = BluetoothConnectionService.getDevice();
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
mSocket = mdevice.createInsecureRfcommSocketToServiceRecord(uuid);
mSocket.connect();
BluetoothConnectionService.setSocket(mSocket);
BluetoothConnectionService.sendMessage(mSocket, "S");
Thread.sleep(1000);
Log.i("BT", "Connected");
} catch (InterruptedException e) {
throw new IOException();
}
} catch (IOException e) {
e.printStackTrace();
try {
Log.i("BT", "trying fallback...");
mSocket = (BluetoothSocket) mSocket.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class}).invoke(mdevice, 2);
mSocket.connect();
BluetoothConnectionService.setSocket(mSocket);
BluetoothConnectionService.sendMessage(mSocket, "S");
Thread.sleep(1000);
Log.i("BT", "Connected");
} catch (Exception e2) {
Log.e("Error", "Couldn't establish Bluetooth connection!");
try {
if (mSocket != null) {
mSocket.close();
}  else {
Log.e("Error", "Could not close socket!");
}
} catch (IOException e1) {
Log.e("Error", "Could not close socket!");
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
final Context context = weakContext.get();
if (context != null) {
super.onPostExecute(result);
try {
if (pd != null) {
if (pd.isShowing()) {
if (context instanceof Configuration) {
onCompleteConfiguration((Configuration) context);
} else if (context instanceof CollectingDetail) {
onCompleteCollectingDetail((CollectingDetail) context);
}
pd.dismiss();
}
}
} catch (final IllegalArgumentException are) {
Log.e("Error", "Illegal Argument Exception!");
} finally {
pd = null;
}
}
}

更新:事实证明,此问题特定于某些Android设备。 我特别遇到此问题的设备是使用两台Dragon Touch V10平板电脑时。 其他设备我没有遇到这个问题。 蓝牙设备基于 RN4677。

您正在使用未公开或已弃用的方法。

虽然较新的Android改进了蓝牙通信,但一些错误可能会挥之不去,尤其是在使用隐藏方法时。确保通信确实关闭,检查设备,以及它是否实际断开连接,并设置为返回广播模式,或者它接受移动到新的蓝牙主站。

就Android认证而言,只有公开声明的方法必须实现,隐藏的可能是,但可能是地狱般的错误。

也检查一下

最新更新