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
PendingIntent
that will start up aService
in the future - Trigger
Service
base 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_COMPLETE
permission - 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
JobService
runs on main thread- Support batching
- If
JobService
run failed,JobScheduler
will return its information and the job can be rescheduled or handled by developers. JobService
must 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
AbstractAccountAuthenticator
andContentProvider
- 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
ContentResolver
withaddPeriodicSync()
- 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?