我有一个可以通过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。
答案 0 :(得分:0)
您正在使用未公开或不推荐使用的方法。
虽然较新的Android改进了蓝牙通信,但某些错误可能会持续存在,尤其是在使用隐藏方法时。确保通讯确实关闭,检查设备,并确保其确实断开连接,并设置为返回广播模式,或者接受移动到新的Bluetooth Master
就Android认证而言,只有公开声明的方法才必须实现,隐藏的方法可能是,但可能像臭虫一样。