我正在开发一个Android应用程序(该应用程序在Android 6上运行):我希望该应用程序在靠近BLE设备(我家里的设备)时向用户发送通知。所以我不断地扫描,我通过一个服务(在后台运行)进行扫描。当手机屏幕打开时,它工作得很好;但是,当屏幕关闭时,几秒钟后,应用程序再也找不到BLE (扫描仍在运行,但没有回调。
if (enable) {
if (mScanning) return;
// Stops scanning after a pre-defined scan period.
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (!mScanning) return;
try {
mScanning = false;
mBluetoothLeScanner.stopScan(mScanCallback);
Log.i(TAG_LOG, "Stop scanning after pre-defined scan periode");
} catch (Exception e){Log.e(TAG_LOG,"mBluetoothLeScanner.stopScan Exception:=>"+e.getMessage());}
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
Log.i(TAG_LOG, "Start scanning ....");
}
private ScanCallback mScanCallback = new ScanCallback() {
//When a BLE advertisement has been found
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
Log.i(TAG_LOG, "Name: "+result.getDevice().getName()+". Adresse: "+result.getDevice().getAddress()+". Rssi: "+result.getRssi());
//scanDevices(false);
if(result.getDevice().getName() != null && result.getDevice().getName().toString().equals(deviceName)){
mDeviceAdress = result.getDevice().getAddress();
mDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAdress);
Log.i(TAG_LOG, "Device found");
scanDevices(false);
}
}
发布于 2020-07-18 18:36:06
你不能让它起作用。扫描是一个非常昂贵的操作,Android不允许在后台进行扫描。而应尝试连接到该设备。我在WorkManager作业中成功地做到了这一点,每15分钟运行一次。电池消耗可以忽略不计,而且非常可靠。请注意,连接状态0x85通常表示设备超出范围,0x80表示已连接到不同的设备(或电话已连接到太多不同的设备)。完整的错误列表位于https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/master/stack/include/gatt_api.h#27
https://stackoverflow.com/questions/62961270
复制相似问题