Background scheduler in Android - Tuong-Nguyen/PreparationEduLog GitHub Wiki
Alarm Manager
- Run or repeat beyond the scope of application lifecycle
- Have ability to wake device
- Fire off a
PendingIntentthat will start up aServicein the future - Trigger
Servicebase on an elapsed interval or a specific clock time - Android batching alarms with similar interval or times together to preserve battery.
- Alarms are wiped out during device reboot. Needs:
- Register
RECEIVE_BOOT_COMPLETEpermission - Reschedule alarms in BroadcastReceiver
- Register
Pros Cons
Pros
- An application needs to perform a local event at exact time or inexact interval. Ex: alarm clock, reminder application
Cons
- It's not compatible for scheduling network-related tasks
Job Scheduler
- Perform
JobSerivce- Criteria: the device is charging, idle, connected to a network or an unmetered network
- Other: at a later time
JobServiceruns on main thread- Support batching
- If
JobServicerun failed,JobSchedulerwill return its information and the job can be rescheduled or handled by developers. JobServicemust override- onStartJob(JobParams params) - runs on main thread
- onStopJob(JobParams params)
Pros Cons
Pros
- Background work, especially networking.
Cons
- It's compatible only with API level 21 and higher
Usage
Sync Adapter
- Could be triggered from data changes in either the server or device or by elapsed time and time of day
- Support batching
- Syncs only when the device is connected to network
- The sync can be transparent or not to users
How to use
- Requires a subclass of
AbstractAccountAuthenticatorandContentProvider - CursorLoader automatically registers a ContentObserver to trigger a reload when data changes.
- Tell local data to sync with the server by:
- Calling
ContentResolver.requestSync() - Sync automatically with
setSyncAutomatically() - Add periodic syncs to
ContentResolverwithaddPeriodicSync()
- Calling
Pros Cons
Pros
- Supports API level 7 and higher
- Not required Google Play Services
Things to consider
Answer these questions:
- Will the scheduler need to exist outside of scope of the application lifecycle?
- Will the app need to schedule networking?
- Which scheduler will allow the support of the most users?