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?