5

In Android 10, some manufacturer comes with the new feature in a battery optimization setting (see the picture). My foreground service getting killed by OS after some time when the screen is off.

I have used the foreground service with notification. This code is working well when the screen is ON in all devices. I am facing this issue in OnePlus and realMe device, both having an android 10 OS.

I want to know, Is there any way to solve this problem? Is there any way to know in my device is having such kind of setting?

Thanks for help!

OnePlus7

mdroid
  • 474
  • 3
  • 15
  • 1
    A foreground service has never guaranteed that it will run forever. It is less likely to be terminated at any point in time, but it still can be terminated. – CommonsWare Jun 10 '20 at 13:54
  • Thanks @CommonsWare, Is there any way to get an "Intelligent Control" setting is exists in the device? Any solution for always keep running my service in the device? – mdroid Jun 10 '20 at 13:59
  • 2
    "Is there any way to get an "Intelligent Control" setting is exists in the device?" -- none that I know of. There is no requirement for a manufacturer to provide APIs for that sort of thing. "Any solution for always keep running my service in the device?" -- that is not possible. Again, even a foreground service can be terminated. Use a foreground service and use `START_STICKY`, so the OS knows that you would like to be restarted if you are terminated. After that, it is up to the device manufacturer, and your app needs to cope with possible "downtime" when your service will not run. – CommonsWare Jun 10 '20 at 14:03
  • Yes, I have used the START_STICKY in the onStartCommand method but it is not restarted when OS has killed the app. Thanks @CommonsWare – mdroid Jun 10 '20 at 14:07
  • you could restart your ForegroundService with a JobScheduler and a BroadcastReceiver on certain system events like SCREEN-ON which require more permissions on the downside. – Christian Jun 10 '20 at 14:19
  • Yes, I have tried with the work manager to schedule a periodic job every 30 minutes. But it will not work when the app is killed by OS. – mdroid Jun 12 '20 at 07:02

1 Answers1

-1

I was getting the same problem, in my case the service gets location in background so, I have to add foregroundServiceType and it works fine. https://developer.android.com/about/versions/10/privacy/changes#app-access-device-location

android:foregroundServiceType="location"
  • 1
    Thansk @Jordan, But I haven't used any location service as a foreground service. This `android:foregroundServiceType="location"` is required when you want to start the foreground service to track the location. – mdroid Dec 04 '20 at 05:49
  • Yes but somehow I have observed adding this flag helps in os not killing the service – Abhriya Roy Apr 05 '23 at 08:48