У меня есть приложение, которое я связываю с устройством Bluetooth через SPP, и я обнаружил, что когда я пытаюсь подключиться к тому же устройству Bluetooth с помощью другого устройства Android, другое устройство Android не может подключиться к устройству Bluetooth, даже когда я закрываюсь моего приложения или отключите питание устройства Bluetooth. Единственное решение - отключение Bluetooth-устройства. Я уверен, что закрыл все свои сокеты и отправил правильную команду отключения на свое устройство Bluetooth; Интересно, почему мое второе устройство Android не подключается к моему устройству Bluetooth, если я не разорву его.
Вот код для подключения:
открытый класс 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. На других устройствах у меня не было этой проблемы. Устройство Bluetooth основано на RN4677.