📅  最后修改于: 2023-12-03 14:48:33.993000             🧑  作者: Mango
In Android development, both WorkManager and JobScheduler are used to schedule and manage background tasks. These tasks can be executed even if the app is not running or the device is in doze mode. In this guide, we will explore the features and differences between WorkManager and JobScheduler.
WorkManager is a Jetpack library introduced by Google that provides a unified API to schedule deferrable, guaranteed background tasks. It offers a backward-compatible solution and chooses the most appropriate method of running tasks based on the device's API level.
To use WorkManager, add the following dependency to your build.gradle file:
dependencies {
def work_version = "2.7.1"
implementation "androidx.work:work-runtime-ktx:$work_version"
}
Define and enqueue a task using a Worker
subclass:
class MyWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): Result {
// Perform background task here
return Result.success()
}
}
val workRequest = OneTimeWorkRequestBuilder<MyWorker>().build()
WorkManager.getInstance(context).enqueue(workRequest)
JobScheduler is an Android system service introduced in API level 21 (Android 5.0 Lollipop) that allows you to schedule background tasks. It is the recommended way to schedule jobs on newer devices.
To use JobScheduler, you need to create a subclass of JobService
:
class MyJobService : JobService() {
override fun onStartJob(params: JobParameters): Boolean {
// Perform background task here
jobFinished(params, false) // Indicate job completion
return false // Job is not rescheduled
}
override fun onStopJob(params: JobParameters): Boolean {
return false // Job should not be retried
}
}
Schedule a job using JobInfo
:
val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
val jobInfo = JobInfo.Builder(jobId, ComponentName(context, MyJobService::class.java))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setRequiresCharging(true)
.build()
jobScheduler.schedule(jobInfo)
Both WorkManager and JobScheduler provide capabilities for scheduling and managing background tasks in Android applications. WorkManager offers better backward compatibility and a more flexible and powerful API, while JobScheduler is recommended for devices running Android 5.0 and higher. Choose the one that best fits your project's requirements and minimum API level.