JobScheduler requires API 21+.
An alternative that works on all versions is the GcmNetworkManager .
It uses JobScheduler in 21+ versions and in its lower versions it uses its own implementation.
To use it, your service must inherit from GcmTaskService.
Declare it in AndroidManifest.xml as follows:
<service
android:name=".MyTaskService"
android:exported="true"
android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
<intent-filter>
<action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
</intent-filter>
</service>
Get GcmNetworkManager:
mGcmNetworkManager = GcmNetworkManager.getInstance(this);
Schedule a recurring task like this:
PeriodicTask task = new PeriodicTask.Builder()
.setService(MyTaskService.class)
.setTag(TASK_TAG_PERIODIC)
.setPeriod(30L)
.build();
mGcmNetworkManager.schedule(task);
At the time the scheduled task is run, the system calls the onRunTask()
method of your service.
Another alternative is the Firebase JobDispatcher that provides a JobScheduler-compatible API.
It works on all versions of API 9 that have Google Play services installed. Backcompatibility is achieved by using GcmNetworkManager.
References: