I was reading Guide To Background Tasks, it's well organized and understandable except a few concepts.
Can anyone differentiate between Deferred and Exact background Tasks with some realtime android examples?
Deferred tasks
Every task that is not directly connected to a user interaction and can run at any time in the future can be deferred. The recommended solution for deferred tasks is WorkManager.
WorkManager makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or the device restarts. See the documentation for WorkManager to learn how to schedule these types of tasks.
Exact tasks
A task that needs to be executed at an exact point in time can use AlarmManager.
To learn more about AlarmManager, see Schedule repeating alarms.
Related
It's mentioned in WorkManager documentation that cancelling a Worker is best-effort
WorkManager makes its best effort to cancel the task, but this is
inherently uncertain--the task may already be running or finished when
you attempt to cancel it
What if i have a use case that it's mandatory that the Worker gets cancelled upon calling one of the cancelling methods?
As you wrote WorkManager can only try with a best-effort to cancel a work. In particular, if a task is scheduled to run, and you cancel it, WorkManager will remove it from the schedule.
However, if the tasks it's already running, WorkManager cannot safely interrupt it. The best option is that you write your Worker class taking care of an external cancellation. This has been covered in the Working with WorkManager talk (around minute 15) recorded at the Android Developer Summit 2018.
To be a good citizen you can pool WorkManager using the method: ListenableWorker.isStopped(). You can combine this with the onStopped callback to cleanup your code when you or the OS request to stop the task.
How to run a service(to perform some task) exactly every 5 minute without any fail. I had a working code for the above requirement using Alarmmanager but its failing since i am trying to target Android 8(Oreo).
Is it possible to achieve my usecase targetting Oreo or not ?
There are lots of things in Android when put together, they won't work as expected. The problem you are facing has been solved by new WorkManager API. From official documentation:
WorkManager chooses the appropriate way to run your task based on such
factors 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 and included
dependencies, WorkManager might use JobScheduler, Firebase
JobDispatcher, or AlarmManager.
So WorkManager will take care of what to run based various factors and makes everything a lot easier and cleaner.
For your scenario, You can use recurring tasks:
https://developer.android.com/topic/libraries/architecture/workmanager#recurring
this question is just to get some ideas on these concepts to see what people in the industry use these for.
If you can just give a few example uses for each of these, I would greatly appreciate it. I know how they work and did read the google documentation on them but I still seem to be having a hard time picking one over the other. I don't need you to explain to me how they work. I am simply asking for a few of their example uses. How you ended up incorporating them into your apps and why you picked them over the others.
Thanks
AlarmManager
Using the AlarmManager to Schedule Tasks at the System Level
The AlarmManager provides access to system-level alarm services. Using the AlarmManager allows an application to schedule tasks that may need to run or repeat beyond the scope of its lifecycle. This allows the application to perform some function even after the application process or all of its Android components have been cleaned up by the system.
Typically, the AlarmManager is used to fire off a PendingIntent that will start up a Service in the future. The AlarmManager triggers Services based on an elapsed interval or at a specific clock time. Both of these options also have the ability to wake up the device when it is asleep if the alarm is urgent.
The benefits of the AlarmManager come into play when using inexact intervals or times to fire off Services. The Android system tries to batch alarms with similar intervals or times together in order to preserve battery life. By batching alarms from multiple applications, the system can avoid frequent device wake and networking.
One concern to consider while using the AlarmManager is that alarms are wiped out during device reboots. Applications need to register the RECEIVE_BOOT_COMPLETE permission in their Android Manifest and reschedule their alarms in a BroadcastReceiver.
Another concern is that a poorly designed alarm could cause battery drain. While the AlarmManager does have the ability to wake devices and set an exact time for an alarm, the documentation mentions that developers should be wary of these features when performing networking. Aside from draining a device’s battery by avoiding batch alarms, setting an exact time for an application to sync with a server could put high strain on a server if every application installation tries to sync with the server around the same time! This can be avoided by adding some randomness to alarm intervals or times.
AlarmManager is a great candidate for scheduling if an application needs to perform a local event at an exact time or inexact interval. Alarm clock or reminder applications are great examples for AlarmManager usage. However, the documentation discourages using AlarmManager for scheduling network-related tasks. Let’s take a look at some better options for networking.
Job Scheduler
JobScheduler helps perform background work in an efficient way, especially networking. JobServices are scheduled to run based on criteria declared in JobInfo.Builder(). These criteria include performing the JobService only when the device is charging, idle, connected to a network or connected to an unmetered network. JobInfo can also include minimum delays and certain deadlines for performing the JobService. Jobs will queue up in the system to be performed at a later time if none of these criteria are met. The system will also try to batch these jobs together in the same manner that alarms are scheduled in order to save battery life when making a network connection.
Developers might be concerned about a scheduler that frequently delays firing off its JobServices. If jobs are frequently delayed and data stale as a result, it would be nice to know about such things. JobScheduler will return information about the JobService such as if it was rescheduled or failed. JobScheduler has back-off and retry logic for handling these scenarios, or developers could handle those scenarios themselves.
Subclassing JobService requires an override of its onStartJob(JobParams params) and onStopJob(JobParams params) methods. onStartJob() is where callback logic for jobs should be placed, and it runs on the main thread. Developers are responsible for threading when dealing with long running jobs. Return true to onStartJob() if separate thread processing needs to occur, or false if processing can occur on the main thread and there is no more work to be done for this job. Developers must also call jobFinished(JobParameters params, boolean needsReschedule) when the job is complete and determine whether or not to reschedule more jobs. onStopJob() will get called to stop or cleanup tasks when initial JobInfo parameters are no longer met, such as a user unplugging their device if that parameter is a requirement.
There might be a lot to think about when implementing a JobService, but it comes with a lot more flexibility than AlarmManager. Another handy feature is that scheduled jobs persist through system reboots.
There is at least one drawback to using JobScheduler. As of the writing of this post, it’s compatable only with API level 21 and higher. Here you can find the distribution of Android devices running various API levels. While there is technically no backport of JobScheduler, a similar tool is GCM Network Manager.
REFERENCE LINK
According to https://github.com/ReactiveX/RxAndroid/issues/257#issuecomment-164263215 . interval is just for active code, and if app is not wake up, it will not work. So how to use interval for background scheduling tasks?
Please DO NOT use this solution:
To use interval from RxJava you'll have to make sure your app's process stays alive. One way to do it is to put use the Observable in a foreground service. This is a bad idea because the service is NOT actively delivering value to the user. Waiting for time to pass is not delivering value for the user. Again please DO NOT use this.
AlarmManager and JobScheduler (or it's backport GcmNetworkManager) are far better choices for repeating background activities. If you use AlarmManager.setInexactRepeating() the system can batch jobs from multiple apps together to save battery. Using JobScheduler enables you to execute your background jobs in specific conditions, eg. when the device is connected to the internet or when battery is more than 20%. (Internet is required to check the weather).
interval from RxJava does have it's usage on Android. It's an excellent replacement for Runnable.postDelayed for relatively short durations. It makes the code shorter and more readable.
If you need to schedule a task that should be run even if app is not active anymore then use AlarmManager.
If you need to schedule a task that should be run only when app is active then you can use Observable.interval() and react on emission to execute some code and please don't forget to unsubscribe from the Observable when appropriate (when Activity is paused, etc) so app won't burn the battery!
I have used background service in for updating tasks like playing with web server frequent times(sending Geo-Location data or send/get web data time-wise) in my android apps and also I have faced many problems(slow process, application hang) for this.
But In my current application I have used the AlarmManager followed by PendingIntents for some tasks which worked well.
So I think its good if I replace each updating tasks which use service with AlarmManager followed by PendingIntents.
Is it the right way or I am going doing a big mistake ?
All kind of suggestions are appreciable.
Thanks in advance.
Services and alarms scheduled with AlarmManager serve different but complementary purposes at times. When you schedule an alarm with one of the set methods, the alarm will be triggered at the specified time and you should handle it on a BroadcastReceiver. This means that your handling has to be responsive and cannot have asynchronous operations. According to the docs:
A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this
function, the system considers the object to be finished and no longer
active. (...) Anything that requires asynchronous operation is not
available, because you will need to return from the function to handle
the asynchronous operation, but at that point the BroadcastReceiver is
no longer active and thus the system is free to kill its process
before the asynchronous operation completes.
In case you want to handle more complex operations, it is advised to start a service for doing so. Even if you use the more recently available goAsync() call on the receiver, you are still expected to be responsive:
This does not change the expectation of being relatively responsive to the broadcast (finishing it within 10s)
So it ultimately depends on what you are trying to achieve, when to use each of these or combine their use.
I don't tell that using Alaram Manager is a big mistake..
Right now to run the background services there are only few options upon which the easy and partially reliable one would be AlarmManager.
Though sometimes the Alarm Manager is not 100% reliable on looking into other categories for doing these operations (like Asynchronous Thread and delay looping techniques) are much more complex and not that much reliable to do the background services.
When we compare the pros and cons of the techniques needed for background services AlarmManager wins the race.
I prefer AlarmManager would be the good option for these kind of background services upon thinking the options open right now to complete the tasks in background.
Hope that Google will comeup with a better solution to handle the background services.