Skip to content Skip to sidebar Skip to footer

Android Bluetooth Le Scanner On Foreground Service Stops Immediately When Screen Turns Off

I have the following BLE foreground service implementation - public class BluetoothForegroundService extends Service { private PowerManager.WakeLock wakeLock; @Override

Solution 1:

I think you are lacking some things.

Android 10 permissions On Android 10, you generally must have obtained ACCESS_BACKGROUND_LOCATION for beacon detection to work when your app is not visible. However, it is possible to scan with only foreground location permission granted and a foreground service if you add android:foregroundServiceType="location" to your foreground service declaration in the manifest. See here for details.

So you need ACCESS_BACKGROUND_LOCATION in order to get scanning results when the screen is off in A10+.

Also, has introduced in A8, (you can see it here), there is a limit of 10 minutes before scan function stops. So I recommend you to use a JobScheduler or a Runnable to make a 9 minutes timer (or 10) and reset the scan. That way you get a long scanning service. This is an example:

 mHandlerUpdate?.removeCallbacksAndMessages(null)

        mHandlerUpdate?.postDelayed(object : Runnable {
            overridefunrun() {
                Log.d(BleService::class.java.simpleName, "run: in runnable handler")
                scanner.stopScan(mScanCallback)

                scanner.startScan(
                    filters,
                    settings,
                    mScanCallback
                )
                mHandlerUpdate?.postDelayed(this, 60000)
            }
        }, 60000)

The handler above resets the scanning every 60 seconds. Is just a demo code. You can modify accoriding to your needs. Remember to removeCallbacksAndMessages when you are done with it.

Also, it is necessary to have Location Services on in order to get results. You can see the why here.

Some other links of interests..

Chet talk

Develpers Android Bt Page

Post a Comment for "Android Bluetooth Le Scanner On Foreground Service Stops Immediately When Screen Turns Off"