Android-job: Run job if internet available, if not, wait until connection

Created on 13 Apr 2018  路  4Comments  路  Source: evernote/android-job

Hi, what would be the easier way to do something like this:

Run the job now if internet is available, if not, run it immediately when internet is restored. I am doing something hacky and I don't think it's the right way to do. This is what I'm doing:

I create my job with "startNow()"

JobRequest.Builder(TAG)
                    .setExtras(extras)
                    .startNow()
                    .build()
                    .schedule()

In onRunJob() I do in the first line:

if (!connection.isConnected) {
    return Result.RESCHEDULE
}

Then I have a broadcast receiver listening from network state changes

override fun onReceive(context: Context, intent: Intent) {
        val internetAvailable = getStatus()

        if (internetAvailable ) {
            val pendingJobs = JobManager.instance().allJobRequests.sortedBy { it.jobId }
            pendingJobs.forEach {
                val job = it.cancelAndEdit()

                job.startNow().build().schedule()
            }
        }
}

Do you know a better way to achieve this?

question

Most helpful comment

I would do something like this and let the JobScheduler handle that

new JobRequest.Builder(your tag)
            .setExecutionWindow(30 minutes, 2 hours)
            .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
            .setRequirementsEnforced(true)
            .build()
            .schedule();

All 4 comments

Unfortunately, it depends on the job scheduling engine used. The JobScheduler should support this feature out of the box, but the AlarmManager (Android 4.X) doesn't. More and more people are using newer devices, so it's not worth to implement this anymore. It's also difficult to implement this for other requirements and in general I don't want to reimplement the job scheduling engine.

@vRallev Okay, so, what would you do in this situation? Is my solution good enough?

I would do something like this and let the JobScheduler handle that

new JobRequest.Builder(your tag)
            .setExecutionWindow(30 minutes, 2 hours)
            .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
            .setRequirementsEnforced(true)
            .build()
            .schedule();

Will this solution trigger job immediately if internet is connected?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

deviant-studio picture deviant-studio  路  5Comments

krokyze picture krokyze  路  3Comments

letos picture letos  路  4Comments

judemanutd picture judemanutd  路  4Comments

Haoxiqiang picture Haoxiqiang  路  3Comments