我有一个应用程序,我通过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;
}
}
}更新:发现这个问题是某些安卓设备特有的。我特别遇到这个问题的设备是在使用两片龙芯V10平板的时候。其他我还没遇到这个问题的设备。蓝牙设备基于RN4677。
发布于 2019-08-29 00:37:19
您正在使用非公开或不建议使用的方法。
虽然较新的Android已经改进了蓝牙通信,但一些bug可能会继续存在,特别是在使用隐藏方法时。确保通信真的关闭,检查设备,并且它实际上断开,并设置回到广播模式,或者它接受移动到一个新的蓝牙主
至于Android认证,只有公开声明的方法必须实现,隐藏的可能是,但可能是错误的地狱。
https://stackoverflow.com/questions/57665322
复制相似问题