Pro*_*oxy 1 android bluetooth-lowenergy android-ble
几天以来,我尝试在我的应用程序中实现 BLE 连接。我知道我尝试连接的设备功能齐全,因此问题一定是我的代码。
我用的是BluetoothLeScanner.startScan()方法。
但回调方法永远不会被调用。
public void startScan() {
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
isScanning = true;
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mainActivityHandler.setMSG("Scan stopped");
isScanning = false;
leScanner.stopScan(scanCallback);
}
}, SCAN_TIME);
mainActivityHandler.setMSG("Start scan");
try {
leScanner.startScan(scanCallback);
} catch (Exception e) {
mainActivityHandler.catchError(e);
}
} else mainActivityHandler.catchError(new Exception("Bluetooth not activated"));
}
Run Code Online (Sandbox Code Playgroud)
我的 CallbackMethod (不知道我是否正确使用 gatt,但这是另一个问题):
private ScanCallback scanCallback = new ScanCallback() {
@Override
public void onBatchScanResults(List<ScanResult> results) {
mainActivityHandler.setMSG("Callback");
isScanning = false;
try {
mainActivityHandler.setMSG("Connected to " + results.get(0).getDevice().getName());
gatt = results.get(0).getDevice().connectGatt(mainActivity, true, bluetoothGattCallback);
BluetoothGattDescriptor descriptor;
for (int i = 0; i < charIDs.length; i++) {
gatt.setCharacteristicNotification(gatt.getService(serviceID[0]).getCharacteristic(charIDs[i]), true);
descriptor = gatt.getService(serviceID[0]).getCharacteristic(charIDs[0]).getDescriptor(charIDs[i]);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
} catch (Exception e) {
mainActivityHandler.catchError(e);
}
}
};
Run Code Online (Sandbox Code Playgroud)
问题是你只是重写了onBatchScanResults方法而不是onScanResult方法。onBatchScanResults仅在以下情况下才会被触发:
ScanSettings模式设置为ScanSettings.SCAN_MODE_LOW_POWER(这是默认设置)ScanSettings.Builder。setReportDelay(long reportDelayMillis)在ScanSettings.Builder.reportDelayMillis - 报告延迟(以毫秒为单位)。设置为 0 可立即通知结果。值 > 0 会导致扫描结果排队并在请求的延迟后或内部缓冲区填满时传送。
例如:
public void startScan(BluetoothLeScanner scanner) {
ScanFilter filter = new ScanFilter.Builder().setDeviceName(null).build();
ArrayList<ScanFilter> filters = new ArrayList<ScanFilter>();
filters.add(filter);
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.setReportDelay(1l)
.build();
Log.i(TAG,"The setting are "+settings.getReportDelayMillis());
scanner.startScan(filters,settings,BLEScan);
}
Run Code Online (Sandbox Code Playgroud)
但是,您可能只想一次获得一次结果,而不是一批结果。要实现这一点,您不必修改 ScanSettings,只需重写onScanResult您的方法ScanCallback即可。
private ScanCallback mScanCallback =
new ScanCallback() {
public void onScanResult(int callbackType, ScanResult result) {
System.out.println(result.getDevice().getName())
// Do whatever you want
};
...
};
Run Code Online (Sandbox Code Playgroud)
不管怎样,我强烈推荐使用RxAndroidBle库。它维护得很好,并且解决了许多开箱即用的 BLE 问题(扫描可能是 BLE 中不太复杂的部分)。
使用该库,可以像这样完成扫描:
Disposable scanSubscription = rxBleClient.scanBleDevices(
new ScanSettings.Builder()
// .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
// .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
.build()
// add filters if needed
)
.subscribe(
scanResult -> {
// Process scan result here.
},
throwable -> {
// Handle an error here.
}
);
// When done, just dispose.
scanSubscription.dispose();
Run Code Online (Sandbox Code Playgroud)