Jobscheduler to run every x hours

Asked

Viewed 330 times

0

I need to run an api access in an interval 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.

The right thing for my purpose is to use it ?

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

If possible post an example of using it.

  • Dude, Google is full of great tutorials. I did a search now and the first result that came is already an excellent tutorial. I only had to type 3 words in the search: job Android Scheduler. Much simpler than writing a whole question.

  • I couldn’t find information about it working in previous versions

1 answer

4

Jobscheduler requires API 21+.

An alternative that works in all versions is the Gcmnetworkmanager.

It uses Jobscheduler in versions 21+ and in lower versions uses its own implementation.

To use it, your service must inherit from Gcmtaskservice.

Declare it on 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 the Gcmnetworkmanager:

mGcmNetworkManager = GcmNetworkManager.getInstance(this);

Schedule a periodic 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 executed, the system calls the method onRunTask() of your service.

More alternatives:

  • Firebase Jobdispatcher that provides a Jobscheduler compatible API.
    Works on all versions from API 9 that have Google Play services installed. Backward compatibility is achieved by using Gcmnetworkmanager.

  • Workmanager

    New api included in the brand new Android Jetpack.
    Uses support libraries, allowing backward compatibility.

References:

  • ramaral, if I’m not mistaken the job Scheduler appeared in version 21, not 23. I would also recommend the Evernote Job Scheduler, but there is another scope :)

  • @Wakim thank you. What misled me was that it is said in Implementing GCM Network Manager on Android that Gcmnetworkmanager uses Jobscheduler in versions 23+.

  • 1

    Weird, either the documentation is wrong or Chet Haase is wrong in this medium post: https://medium.com/google-developers/developing-for-android-iv-e7dc4ce0a59. Normal in the Android world hehe, not everything is documented right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.