JobScheduler to run every x hours

1

I need to run an api access in a range of hours, for example every 3 hours. I was looking for ways to do this, I read about AlarmManager and about this JobScheduler that seems to be the latest.

Is it correct for my purpose to use it?

Is it compatible with previous versions of android? (my minimum version is 17).

If possible, post an example of using it.

    
asked by anonymous 29.07.2017 / 02:33

1 answer

2

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:

29.07.2017 / 18:38