android – 如何重启BluetoothLeScanner?
作者:互联网
我在Android端使用BluetoothLeScanner将Android设备连接到iOS.这一切都是第一次完美运作.
问题是,在连接到其中一个已发现的iOS设备后,我停止扫描(stopScan(scanCallback))以保存能量.
如果以后连接设备由于某种原因断开连接我再次开始扫描…但似乎在’重新启动’扫描后不再工作 – 它没有发现任何更多的设备…不知道为什么但我被迫重新启动应用程序.
任何想法如何解决这一问题?
我也使用ScanFilter按UUID过滤设备,并使用ScanSettings.SCAN_MODE_BALANCED进行扫描模式.
这是代码:
private void startScanner() {
BluetoothManager bluetoothManager = (BluetoothManager) activity.getSystemService(activity.BLUETOOTH_SERVICE);
BluetoothAdapter adapter = bluetoothManager.getAdapter();
scanner = adapter.getBluetoothLeScanner();
ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
scanner.startScan(scanFilters(), settings, scanCallback);
System.out.println("Scanner started");
}
private List<ScanFilter> scanFilters() {
ScanFilter filter = new ScanFilter.Builder().setServiceUuid(THE_BT_UUID).build();
List<ScanFilter> list = new ArrayList<ScanFilter>(1);
list.add(filter);
return list;
}
private final ScanCallback scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
if (device != null) {
callback.foundRemoteDevice(BluetoothCentral.this, device);
}
}
}
public void connectToDevice(BluetoothDevice device) {
if (gatt == null) {
gatt = device.connectGatt(activity, false, gattCallback);
scanner.stopScan(scanCallback);
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
System.out.println("onConnectionStateChange; status: " + status + ", state: " + newState);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
System.out.println("STATE_CONNECTED");
if (!startedServiceDiscovery) {
gatt.discoverServices();
startedServiceDiscovery = true;
}
break;
case BluetoothProfile.STATE_DISCONNECTED:
callback.didDisconnectFromDevice(BluetoothCentral.this, gatt.getDevice());
gatt = null;
startScanner();
break;
default:
System.out.println("STATE_OTHER");
}
}
}
请注意,我在connectGatt调用之后立即停止扫描,并在获得BluetoothProfile.STATE_DISCONNECTED回调时再次启动它.
解决方法:
正如我的评论,帮助您解决问题,我在这里添加我的评论作为答案.
Code seems ok to me, did you try adding logs in onScanResult method.
to check if device is getting detected but something else is failing.
One more thing, I see if I restart scanning it takes time to get the
device detected in comparison of first scanning.
标签:android,bluetooth,bluetooth-lowenergy,android-bluetooth 来源: https://codeday.me/bug/20190702/1361147.html