JobScheduler Android Oreo Issue - android

In my current application for a company Im having a ForegroundService that is running while the workers are on duty (logged in to the app).
It is important to keep that foreground service running while users are logged in. To recover from cases where this foreground service gets killed somehow (User task swipe accidently or System kill) ive implemented a periodic JOB with Jobscheduler which reactivates the ForegroundService in case it gets shut down. This technique works well pre Android 8 OREO. START_STICKY and other techniques alone did not do the trick for me.
In Android 8, as soon as the foreground service gets killed, the periodic job gets killed as well. Im getting the notification in logcat that the job is not allowed to run. To my understanding, Jobs schould be able to run even when app is in background or killed. And its working on pre OREO devices the way it should.
To my knowledge, I can fix that by enable the option "autostart" in app settings. But since there is no way to know if employees tunred that on, its not a reliable thing as well.
So my questions:
- Why does the Job scheduler stops working as it should in Android 8?
- Are there any other reliable techniques I could use to let my ForegroundService recover from shutdowns in ANDROID OREO?
Ive read https://medium.com/exploring-android/exploring-background-execution-limits-on-android-oreo-ab384762a66c but that did not answer my questions
Thank you very much

did you try to put
.setPersisted(true)
Note: Requires the RECEIVE_BOOT_COMPLETED permission.
you can also see this question.
Job Scheduler not running on Android N

reading some references:
1- The services in andreo oreo if posses a buggle oreo will kill it for energy loss in 7 is a warning but in 8 applies more strict
2 - The jobs scheduler has a time of 15 minutes and avaces is not executed in the precise time debit that they look for the precise moment to execute the event without that the battery of the cellular one is descaste
I recommend that you use this library that provides evernote that is very good and very specific:
https://github.com/evernote/android-job

Related

Which is better alarm manager or workmanager

I want to show notification at certain time and day by using retrofit2 networking.
But in alarm manager doc. It mentioned that isn't proper fpr networkong job. But in workmanager doc it says for the exact time job use alarm manager. What would be better for me to use? Alarm manager nor work manager
Android has introduced so many things that need to save battery life like:
Doze version 1 - API 6.0
Doze version 2 - API 7.0
https://developer.android.com/about/versions/nougat/android-7.0-changes#perf
Removing CONNECTIVITY_CHANGE Manifest declaration and others in - API 7.0
https://developer.android.com/guide/components/broadcasts
Background execution limitations in API 8.0
https://developer.android.com/about/versions/oreo/background#services
App Standby Buckets API 9.0 (Upgraded in Android 12)
https://developer.android.com/about/versions/pie/power#buckets
https://developer.android.com/about/versions/12/behavior-changes-all#restrictive-app-standby-bucket
https://developer.android.com/topic/performance/appstandby
Battery Saver improvements in API 9.0
https://developer.android.com/about/versions/pie/power#battery-saver
https://developer.android.com/topic/performance/power/power-details
App Hibernation in 11 and 12 API.
All this stuff were not done for us to be able to do whatever we want by using the WorkManager. WorkManager was created to integrate all this requirements in a single API.
That is why the idea behind it is:
do some work
finish it at some point for sure(even if the device is restarted)
SAVE THE BATTERY AND NETWORK USAGE BY COMPLYING WITH THE ABOVE
Before that you had the AlarmManager to wake up in exact time
Services to keep the app process alive by giving your application priority. You still have them with the exclusion that now the starting services in the background are problematic. As per:
https://developer.android.com/about/versions/oreo/background#services
So if you want to do things like this you need to fully understand the Android API and limitations.
If you need help in StackOverflow - you need to fully understand your use case, you should have really put your mind into trying to understand it, communicate all these limitations with your PMs and explain to them that the Android Ecosystem is pretty complicated, there are a lot more applications besides the one you are writing and they all compete for resources. We can't do everything that we want. It is highly unlikely for the user itself to want to do long-running operations in exact timing starting from the background. But it might need it. Also, you have the option to ask to be exempted from battery optimization:
https://developer.android.com/training/monitoring-device-state/doze-standby#support_for_other_use_cases
Also, some people try to use Push notifications, but it is highly unlikely that it will work in your case. You can send high-priority ones, but if android detects that the user is not interacting with the notification they will lose its priority. And if you do not have the priority and also want to do a long-running operation - you need to create... a Work in the WorkManager :)
But long story short:
what will wake you up:
AlarmManager is exact
WorkManager is not
what will keep you alive:
Service
WorkManager(it uses its own service)

What should be used for background tasks instead of foreground service when app is killed?

In my app I want to show notification on exact time when the app is working in background or even it is closed. I used AlarmManager and service with BroadcastReceiver to show notification. The latest versions of android doesn't allow to run service in background after app closed and foreground service is consuming battery, slowing down the device etc.. I wonder if I could use something else can work even app is closed and show the notifications. I've heard of WorkManager and JobScheduler for that kind of operations but can they do the work even if app is closed?
Foreground services is not consuming more battery and not slowing down device, just notification is shown.
And the answer is basically it is not possible to make continuous background service on new android API's. You only can schedule tasks with tools like WorkManager, JobScheduler and so on.
These days I think WorkManager is the answer because Android team is focused on it this year.
Also even continuous foreground services gets killed after some time.... To avoid that 2 things has to be done:
Native battery optimization for app should be disabled.
Phone manufacturer (another battery optimization) has to be also disabled for specific app.....
I know it is worst user experience, and they throwing away half smart things that phone can do, but life is life :)

Android Oreo killing background services and clears pending alarms, scheduled jobs after entering doze mode

My app has a background service running that gets users current location and update it to a server every five minutes. To run this location update process continuously, I use alarm manager to set its next execution time from the service itself. However, when I install the app in my Nokia 6 running Android 8.1 it works for some time and if I keep the phone idle for some time, my service will get killed with the next alarms by the application also being cleared from system alarm manager. My guess was that the idle time makes the phone enter doze mode. However, I don't understand why the alarm managers got cleared. To my understanding, the doze mode should open up maintenance windows periodically to execute any pending tasks.
To mitigate this issue, I tried to apply a JobScheduler service on top of AlarmManager, which runs every 15 minutes. Purpose of this jobscheduler was to re-start the service which has the alarmmanager in it, so even if it gets killed and the alarm is cleared, jobscheduler would re-up the service.
After I tested this patch and keeping it for some time to go into idle mode, it resulted in getting both JobScheduler Service and Service which has the alarm in it killed with the scheduled jobs and alarms getting cleared from the system.
It is said in the Android documentation that we can use JobScheduler to mitigate its background execution limitations. And to test this out I forced killed the two services when I tested the app, but the already scheduled job did not get cleared, and it made the service with the alarm run again successfully. I don't understand the reason for this behavior, although the Evernote guys give an explanation that could match this scenario in here Android Job by Evernote
Any ideas for this abnormal behavior?
Test Environment Details
Device : Nokia 6 (TA-1021)
OS : Android 8.1.0
You would not be able to run background services long running in Oreo as there are behaviour changes, now Oreo to optimise system memory, battery etc, it kills background service, to solve your issue you should use foreground service.
Have a look at Background execution limits https://developer.android.com/about/versions/oreo/android-8.0-changes
A suggestion from me, if you can use FCM then go for it, becasue apps like WeChat, Facebook uses it, to deliver notifications and they don't face any problem...
Hope this helps in understanding the issue....
In Doze more, the alarms do not get reset, but get deferred to a later time. You have two mainstream options here:
Use either setAndAllowWhileIdle() or setExactAndAllowWhileIdle(). However, these too can fire at the maximum frequency of 1 time per 9 minutes. So you'll have to decrease the frequency at which you get location in your app.
Use a foreground service by way of showing a foreground notification. Everyone does that (apps like Uber, Google Maps etc). That way, your service won't get killed, and be treated as though you have an app open.
I'm currently facing the same issue and doing the same workaraound like you do. That is, setting the Jobscheduler to a periodic job to launch my Foreground Service every 15 min in case it is getting killed for whatever reasons like a killed task. This works like a charm on pre Oreo Versions.
For Oreo the only solution I am awared of at the moment is, to allow the app to autostart in the settings. Under installed apps that is. Then it should work like pre Oreo again.
What Ive heard but not tested yet, is to set the setPersisted(true) option in the Job Scheduler.
Let me know if that helps
I assumed currently DOZE mode not allowed to background service so you need to find a way that DOZE mode will not affect on your app.To solve your issue you should use foreground service. or make some battery setting. Any way my better option is you should go with Firebase Cloud Messaging

Android. Is WorkManager running when app is closed?

I want to schedule nightly database updates. So I use new Android WorkManager. My understanding is that once scheduled it will always run in the background independently from the app's lifecycle.
Is that right? My first tests show that Work is only being performed when the app is running.
val locationWork = PeriodicWorkRequest.Builder(UpdateDatabaseWorker::class.java, 24, TimeUnit.HOURS)
.addTag("DATABASE_UPDATE_SERVICE")
.build()
WorkManager.getInstance().enqueue(locationWork)
Based on various issues reported on the WorkManager bugtracker, their documentation is not completely precise about the exact behavior of the WorkManager in such edge cases.
On certain devices, apps are force stopped when the app is cleared from task manager, so that part is expected. ... source
Unfortunately, some devices implement killing the app from the recents menu as a force stop. Stock Android does not do this. When an app is force stopped, it cannot execute jobs, receive alarms or broadcasts, etc. So unfortunately, it's infeasible for us to address it - the problem lies in the OS and there is no workaround. source
The only issue that we have come across is the case where some Chinese OEMs treat swipe to dismiss from Recents as a force stop. When that happens, WorkManager will reschedule all pending jobs, next time the app starts up. Given that this is a CDD violation, there is not much more that WorkManager can do given its a client library. source
To add to this, if a device manufacturer has decided to modify stock Android to force-stop the app, WorkManager will stop working (as will JobScheduler, alarms, broadcast receivers, etc.). There is no way to work around this. Some device manufacturers do this, unfortunately, so in those cases WorkManager will stop working until the next time the app is launched. source
With intense testing of a OneTimeWorkRequest (without constraints) on a Pixel 2 XL with stock android the behavior is the following:
Task manager close:
Work continues (after a bit)
Reboot device (work running):
Work continues after reboot done
App info "Force stop":
Work stops, will only continue when app is started again
Reboot device (work was "Force Stopped"):
Work does not continue until the app is started again
You can find a complete list of different OEM behaviors on dontkillmyapp.com. It seems the Android team also acknowledges this issue and added a test for this into their CTS test for Android Q. source
My understanding is that once scheduled it will always run in the
background independently from the app's lifecycle. Is that right?
Yes. Based on the documentation
The task is still guaranteed to run, even if your app is force-quit or
the device is rebooted.
WorkManager chooses the appropriate way to run your task based on factors such as the device API level and the app state. If WorkManager executes one of your tasks while the app is running, WorkManager can run your task in a new thread in your app's process. If your app is not running, WorkManager chooses an appropriate way to schedule a background task--depending on the device API level.
WorkManager might use JobScheduler, Firebase JobDispatcher, or AlarmManager depending on the API level. It will repect the Doze and conaider all other constraints before executing the Work. You can expect some delay in Doze mode since it could wait for maintenance window.
Note:
WorkManager is intended for tasks that require a guarantee that the system will run them even if the app exits, like uploading app data to a server. It is not intended for in-process background work that can safely be terminated if the app process goes away; for situations like that, we recommend using ThreadPools.
This is what documentation is saying:
Note: WorkManager is intended for tasks that require a guarantee that the system will run them even if the app exits, like uploading app data to a server. It is not intended for in-process background work that can safely be terminated if the app process goes away; for situations like that, we recommend using ThreadPools.
But there must be some condition. if that condition meet then WorkManager will run the task (this is important). Conditions like "only while device is charging and online"
Read this carefully, The WorkManager attempts to run your task at the interval you request, subject to the constraints you impose and its other requirements.
Here I found a good tutorial about how to use WorkManager for scheduling tasks : https://android.jlelse.eu/how-scheduling-work-with-new-android-jetpack-component-workmanager-852163f4825b

Services stopping automatically from android OS 5.1.1

I am working on an application related to Voip & IM (chatting application). Till android OS 5.0 it is working good and no issues from client also. But from android OS 5.1.1 onwards we are facing issues.
Issues:
If the app is in foreground and if device goes to sleep mode it is working good.
If the app is in background and if device goes to sleep mode after 10 minutes all the services are stopping automatically.
Testing:
For testing I created one timer task to print logs for every 1 minute. So when I close the application (means if the app is in background)
Till android OS 5.0 logs are printing continuously.
From android OS 5.1.1 onwards after going to sleep mode, after 10 minutes logs are not printing. Timer task is stopping
Same problem I am facing for my application also.
After doing some R&D I came to know regarding doze mode and app optimization. Is it anyhow related to stop services automatically running in background.
If yes, can anyone please let me know how to overcome this issue.
This is new thing which google done to prevent unwanted battery usage.
For new versions the background services are restricted for better battery life. The android service consumes almost same as the application running in foreground. So even though app is not running its services may be running and using memory and battery.
If you have to use any kind of background process try to use Job Scheduler which may be something useful for you.
The Job Scheduler groups the task and execute the background task based on the constraints we provide in the implementation.
This have a limitation it support on minimum API 21
To support on lower version you can use Firebase JobDispatcher which support from API 9.
I personally prefer Firebase JobDispatcher
This link help you to understand more about scheduler and its implementation.

Categories

Resources