Reputation: 13
I have an app where I use a foreground service to start a number N of threads that sleep most of the time and sometimes wake up to do some measurements.
I used foreground services because I need that these measurements must be done at specific and exact time without background limitations introduced by Android 8.0.
This seems to work and from documentation seems that there are no problem, but I read also about JobScheduler.
There is an advantage to use Jobs to schedule work at specific accurate time or my solution can be used without problems.
Upvotes: 0
Views: 3429
Reputation: 1374
First a fact
In JobScheduler
, the System execute your Job(Task) in application's JobService
and the JobService
class also extend the same Service
class that we use to define Foreground Service
. So by using the both, we can execute code in background
Now the main difference is, Foreground Service
is always running(by showing notification to user) and consuming the battery and memory of the user even, if your threads are sleeping and no code is executing.
As it's running always you can do whatever you want precisely at any moment of time. maybe it's good for your app's point of view but it's bad for user. your app draining the battery unnecessarily and consuming the RAM.
To address this problem we got JobScheduler
. you can Schedule a job to be executed based on some criteria. Your app will only wake when the criteria is met, but it's not precise.it depends on many factors like doze mode etc.
you can look more about that here
The conclusion is
If your task is not needed to be execute at exact time then you should use JobScheduler
(recently WorkManager
is better as it use JobScheduler
internally and more advance) to save your user's battery
and according official document
WorkManager is intended for tasks that are deferrable—that is, not required to run immediately—and required to run reliably even if the app exits or the device restarts.
Upvotes: 4
Reputation: 5453
For your use case, you will be better off using a WorkManager
which according to the android documentation, uses JobScheduler
on API 23+ and a combination of BroadcastManager
and AlarmManager
on API 14 - 22.
With a WorkManager
your jobs will run reliably even if your app exits or the device restarts.
https://developer.android.com/topic/libraries/architecture/workmanager
Upvotes: 0