Bluetooth development: the background mode of Android 8.1 and above fails to turn on scanning

Keywords: Android

In Android 8.1 and above, there is no problem scanning Bluetooth under normal conditions, but when the App is in the background, the scanning method cannot be turned on and the following prompt is provided

        BtGatt.ScanManager: Cannot start unfiltered scan in screen-off. This scan will be resumed later: 9

This is because the scan method you enable is not set with a scan filter. In Android 8.1 and above systems, to enable scanning in the background mode, you must associate the scan filter, so as to run perfectly in the background mode

//Set Bluetooth scan filter set
    private List<ScanFilter> scanFilterList;
    //Set Bluetooth scan filter
    private ScanFilter.Builder scanFilterBuilder;
    //Set Bluetooth scan settings
    private ScanSettings.Builder  scanSettingBuilder;
 
  
    private List<ScanFilter> buildScanFilters() {
        scanFilterList = new ArrayList<>();
        // Filter the device to be connected through the service UUID filter to search the GATT service UUID
        scanFilterBuilder = new ScanFilter.Builder();
        ParcelUuid parcelUuidMask = ParcelUuid.fromString("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF");
        ParcelUuid parcelUuid = ParcelUuid.fromString("0000ff07-0000-1000-8000-00805f9b34fb");
        scanFilterBuilder.setServiceUuid(parcelUuid, parcelUuidMask);
        scanFilterList.add(scanFilterBuilder.build());
        return scanFilterList;
    }
 
    private ScanSettings buildScanSettings() {
        scanSettingBuilder = new ScanSettings.Builder();
        //Set the scan mode of Bluetooth LE scan.
        //Scan with the highest duty cycle. It is recommended to use this mode to run in the foreground only when the application is in this mode
        scanSettingBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
        //Set the matching mode of Bluetooth LE scan filter hardware matching
        //In active mode, hw can determine the match faster even if the signal strength is weak. There are few sightings / matches in a period of time.
        scanSettingBuilder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
        //Set the callback type of Bluetooth LE scan
        //Trigger a callback for each Bluetooth advertisement matching the filter conditions. If no filter is active, all advertising packages are reported
        scanSettingBuilder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
        return scanSettingBuilder.build();
    }
 
 
    //Call scan on method
    mBluetoothAdapter.getBluetoothLeScanner().startScan(buildScanFilters(), buildScanSettings(), mLeScanCallback);

To put it bluntly, set ScanFilters and ScanSettings

Posted by rigbyae on Mon, 11 Nov 2019 12:30:39 -0800