Однако после успешного подключения и отключения устройства в первом активности, сканирование второго действия не может найти ранее подключенное устройство. Он больше не отображается в результатах сканирования. Я убедился, что устройство было успешно отключено и продолжало транслировать информацию, когда второе устройство сканировало. Я очень озадачен тем, что вызвало эту проблему. Мы будем очень благодарны за любую помощь!
Вот скелетный код моего первого действия:
Код: Выделить всё
public class BluetoothActivity {
private static final String SERVICE_UUID_STRING = "12340000-58fa-4b77-8f3b-72fd2cbaa335";
private static final String CALIBRATE_CHAR_UUID_STRING = "1234efab-58fa-4b77-8f3b-72fd2cbaa335";
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private BluetoothGatt mBluetoothGatt;
private boolean tag10connected = false;
private Handler scanTimeoutHandler = new Handler();
private Runnable scanTimeoutRunnable = new Runnable() {
@SuppressLint("MissingPermission")
@Override
public void run() {
stopScanning();
toastMessage("Scan timed out without finding target device!");
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
};
@SuppressLint("MissingPermission")
public void startScanning() {
Log.e("BLE", "startScanning: mBluetoothAdapter.isEnabled() = " + mBluetoothAdapter.isEnabled());
mBluetoothLeScanner.startScan(mScanCallback);
}
@SuppressLint("MissingPermission")
private void stopScanning() {
Log.e("BLE", "stopScanning: mBluetoothLeScanner = " + mBluetoothLeScanner);
toastMessage("Scanning finished!");
mBluetoothLeScanner.stopScan(mScanCallback);
scanTimeoutHandler.removeCallbacks(scanTimeoutRunnable);
}
@SuppressLint("MissingPermission")
private void connectToDevice(BluetoothDevice device) {
mBluetoothGatt = device.connectGatt(this, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
}
@SuppressLint("MissingPermission")
private void disconnectDevice() {
if (mBluetoothGatt != null) {
BluetoothDevice device = mBluetoothGatt.getDevice();
Log.e("BLE", "Trying to disconnect: " + device.getName());
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
private ScanCallback mScanCallback = new ScanCallback() {
@SuppressLint("MissingPermission")
@Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
if (device.getName() != null && device.getName().equals("TOILET")) {
tag10connected = true;
stopScanning();
connectToDevice(device);
}
}
};
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@SuppressLint("MissingPermission")
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, final int newState) {
if (newState == BluetoothGatt.STATE_CONNECTED) {
Log.e("BLEConnection", "Connection Built!");
toastMessage("Connected!");
disconnectDevice();
} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
Log.e("BLEConnection", "Disconnected!");
toastMessage("Disconnected!");
}
}
@SuppressLint("MissingPermission")
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.e("BLE", "onServicesDiscovered called with status: " + status);
if (status == BluetoothGatt.GATT_SUCCESS) {
BluetoothGattCharacteristic characteristic = gatt.getService(UUID.fromString(SERVICE_UUID_STRING))
.getCharacteristic(UUID.fromString(CALIBRATE_CHAR_UUID_STRING));
characteristic.setValue(String.valueOf(0));
gatt.writeCharacteristic(characteristic);
}
}
@SuppressLint("MissingPermission")
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
disconnectDevice();
}
}
};
public void toastMessage(String data) {
Toast.makeText(this, data, Toast.LENGTH_LONG).show();
}
}
Код: Выделить всё
public class IMUCalibrationActivity {
private static final String SERVICE_UUID_STRING = "45670000-58fa-4b77-8f3b-72fd2cbaa335";
private static final String CALIBRATE_CHAR_UUID_STRING = "45671111-58fa-4b77-8f3b-72fd2cbaa335";
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private BluetoothGatt mBluetoothGatt;
private Handler scanTimeoutHandler = new Handler();
private Runnable scanTimeoutRunnable = new Runnable() {
@SuppressLint("MissingPermission")
@Override
public void run() {
stopScanning();
toastMessage("Scan timed out without finding target device!");
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
};
@SuppressLint("MissingPermission")
public void startScanning() {
Log.e("BLE", "startScanning: mBluetoothAdapter.isEnabled() = " + mBluetoothAdapter.isEnabled());
toastMessage("Scanning...");
mBluetoothLeScanner.startScan(mScanCallback);
scanTimeoutHandler.postDelayed(scanTimeoutRunnable, 10000); // 10 seconds timeout
}
@SuppressLint("MissingPermission")
private void stopScanning() {
Log.e("BLE", "stopScanning: mBluetoothLeScanner = " + mBluetoothLeScanner);
toastMessage("Scanning finished!");
mBluetoothLeScanner.stopScan(mScanCallback);
scanTimeoutHandler.removeCallbacks(scanTimeoutRunnable);
}
@SuppressLint("MissingPermission")
private void connectToDevice(BluetoothDevice device) {
mBluetoothGatt = device.connectGatt(this, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
}
@SuppressLint("MissingPermission")
private void disconnectDevice() {
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
Intent nextStep = new Intent(IMUCalibrationActivity.this, TimeSyncActivity.class);
startActivity(nextStep);
finish();
}
}
private ScanCallback mScanCallback = new ScanCallback() {
@SuppressLint("MissingPermission")
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
if (device.getName() != null && device.getName().equals("TOILET")) {
stopScanning();
connectToDevice(device);
}
}
};
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@SuppressLint("MissingPermission")
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, final int newState) {
runOnUiThread(() -> {
if (newState == BluetoothGatt.STATE_CONNECTED) {
Log.e("BLEConnection", "Connection Built!");
toastMessage("Connected!");
mBluetoothGatt.discoverServices();
} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
Log.e("BLEConnection", "Disconnected!");
toastMessage("Disconnected!");
}
});
}
@SuppressLint("MissingPermission")
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.e("BLE", "onServicesDiscovered called with status: " + status);
if (status == BluetoothGatt.GATT_SUCCESS) {
BluetoothGattCharacteristic characteristic = gatt.getService(UUID.fromString(SERVICE_UUID_STRING))
.getCharacteristic(UUID.fromString(CALIBRATE_CHAR_UUID_STRING));
characteristic.setValue(timestampGenerator());
gatt.writeCharacteristic(characteristic);
Log.e("TimeWorker", "Writing to characteristic: " + gatt.writeCharacteristic(characteristic));
}
}
@SuppressLint("MissingPermission")
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
BluetoothGattCharacteristic calibrationCharacteristic = gatt.getService(UUID.fromString(SERVICE_UUID_STRING))
.getCharacteristic(UUID.fromString(CALIBRATE_CHAR_UUID_STRING));
gatt.readCharacteristic(calibrationCharacteristic);
}
}
@SuppressLint("MissingPermission")
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
Log.e("BLE", "characteristic read: " + characteristic.toString());
if (status == BluetoothGatt.GATT_SUCCESS) {
final byte[] data = characteristic.getValue();
float value = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getFloat();
Log.e("Got value after calibration", String.valueOf(value));
disconnectDevice();
}
}
};
}
Я также попытался очистить PendingScanResults перед началом сканирования во втором действии. Но это тоже не работает. Устройство по-прежнему не отображается.
Я проверил, могут ли другие приложения сканировать это устройство. Поэтому я переключился на nRFConnect для поиска этого устройства, и устройство появилось. Интересно, что когда я снова переключился на это приложение после сканирования с помощью nRFConnect, устройство смогло появиться при сканировании. Я действительно не понимаю, что происходит и что мне следует сделать, чтобы решить эту проблему. Если у вас есть какие-либо предложения, пожалуйста, дайте мне знать! Спасибо большое!
Подробнее здесь: https://stackoverflow.com/questions/788 ... connection
Мобильная версия