Home > Mobile >  BLE scanner on Android 12 not emit devices in Foreground service after phone reboot
BLE scanner on Android 12 not emit devices in Foreground service after phone reboot

Time:08-04

I have Android 10 and Android 12 phones. BLE scanner works fine after rebooting the first one, but doesn't work on the second one.

App has all required permissions requested in runtime:

    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30"/>
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="23"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

GPS and Bluetooth are enabled on the phone.

After rebooting, Foreground service is started from the broadcast receiver (Intent.ACTION_BOOT_COMPLETED).

This service then starts the BLE scanner with the scan filter:

bleAdapter.bluetoothLeScanner.startScan(filters, settings, callback)

It's successfully registered in system (BluetoothLeScanner: onScannerRegistered() - status=0 scannerId=7 mScannerId=0), but there are no devices in the scanner callback on Android 12.

What is the reason and how to solve this problem?

CodePudding user response:

Your app is missing the BLUETOOTH_SCAN and BLUETOOTH_CONNECT runtime permissions for API 31 and above. The BLUETOOTH_SCAN is for accessing the ble scan results and the latter is for accessing and communicating with remote devices, hence makes use of the APIs like BluetoothDevice. You need to implement this permissions in your code where you access to these APIs. Also have a look at Target Android 12 or higher.

CodePudding user response:

BLE scanner in service started after phone reboot requires android.permission.ACCESS_BACKGROUND_LOCATION permission at runtime - Allow all the time in location permission settings page (not Allow only while using the app). It's not enough to only put it in AndroidManifest.

More about permission here: https://developer.android.com/training/location/permissions#request-background-location

  • Related