推荐使用WorkManager来代替JobIntentService。
以下是使用WorkManager的示例代码:
dependencies {
def work_version = "2.4.0"
implementation "androidx.work:work-runtime:$work_version"
}
public class MyWorker extends Worker {
public MyWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
// todo: 执行你的任务
return Result.success();
}
}
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(MyWorker.class).build();
WorkManager.getInstance(context).enqueue(request);
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(MyWorker.class)
.setInitialDelay(delay, TimeUnit.SECONDS)
.build();
WorkManager.getInstance(context).enqueue(request);
PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(MyWorker.class, period, TimeUnit.SECONDS)
.setInitialDelay(delay, TimeUnit.SECONDS)
.build();
WorkManager.getInstance(context).enqueue(request);
使用WorkManager可以解决Android JobIntentService被弃用的问题,并且提供更加灵活的定时任务和延时任务的支持。