Reputation: 41
I can'y get working BLE scan in background with Foreground service on Android 10. My application have in manifest FOREGROUND_SERVICE and gets premissions ACCESS_FINE_LOCATION and ACCESS_BACKGROUND_LOCATION from user on start. Then it starts Foreground service with BLE Scan. When screen is on the service doing scan and find devices, but when screen is off foreground service stop working and scan is stopping.
Starting service:
Intent serviceIntent = new Intent(context, BTService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent);
} else {
context.startService(serviceIntent);
}
Make it foreground:
startForeground(BT_SERVICE_ID, notification);
I am tried to make notification from service:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(getString(R.string.service))
.setContentText((new Date()).toString())
.setSmallIcon(R.drawable.ic_service)
.build();
notificationManager.notify(BT_SERVICE_ID, notification);
handler.postDelayed(runnable, delay);
}
};
int delay = 30000;
And send it from foreground service every 30 seconds:
handler.postDelayed(runnable, delay);
But it don't work too. Why foreground service stops when screen is off?
Upvotes: 4
Views: 2330
Reputation: 603
Answer: according to Adnroid documentation, if you don't use scan filters (i.e. you scan for all available devices) scanning is stopped when screen is off to save power. Scanning is resumed when screen is turned on again.
My case: I develop Android 10 app using React Native. Scanning inside a foreground service with application being not active stops in few minutes even if the screen remains on. If you turn the screen off, the scanning stops immediately.
Upvotes: 2
Reputation: 21
Please check the location permission. Since the Android 10, can't get "Allow all the time" option of the location permission.
So, you need to convince the user to set it up.
If you want to use BLE on the background, the location permission must be set to "Allow all the time".
Upvotes: 2