Last active
December 3, 2018 18:19
-
-
Save JakeSteam/4d87c6472914c714214d9511db340b09 to your computer and use it in GitHub Desktop.
Repeating background tasks on Android using Kotlin and JobDispatcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<service | |
android:name=".JobScheduler" | |
android:exported="false"> | |
<intent-filter> | |
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE" /> | |
</intent-filter> | |
</service> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dependencies { | |
implementation 'com.firebase:firebase-jobdispatcher:0.8.5' | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.util.Log | |
import com.firebase.jobdispatcher.* | |
class JobScheduler : JobService() { | |
override fun onStartJob(job: JobParameters): Boolean { | |
Log.d("JobScheduler", "Job started") | |
when (job.tag) { | |
SIMPLE_JOB_TAG -> simpleJob(job) | |
else -> return false | |
} | |
return true | |
} | |
override fun onStopJob(job: JobParameters?): Boolean { | |
return true | |
} | |
private fun simpleJob(job: JobParameters) { | |
Log.d("JobScheduler", "Ran job ${job.tag}") | |
jobFinished(job, false) | |
} | |
companion object { | |
private const val SIMPLE_JOB_TAG = "uk.co.jakelee.scheduledjobs.job" | |
fun scheduleJob(context: Context) { | |
val dispatcher = FirebaseJobDispatcher(GooglePlayDriver(context)) | |
val exampleJob = dispatcher.newJobBuilder() | |
.setService(JobScheduler::class.java) | |
.setTag(SIMPLE_JOB_TAG) | |
.setRecurring(true) | |
.setLifetime(Lifetime.FOREVER) | |
.setReplaceCurrent(true) | |
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL) | |
.setConstraints(Constraint.ON_UNMETERED_NETWORK, Constraint.DEVICE_CHARGING) | |
.setTrigger(Trigger.executionWindow(5, 10)) | |
dispatcher.mustSchedule(exampleJob.build()) | |
Log.d("JobScheduler", "Scheduled job") | |
} | |
fun cancelJobs(context: Context) { | |
FirebaseJobDispatcher(GooglePlayDriver(context)).cancelAll() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment