android-job是一个可以在后台进行延时处理的库。即使你没有操作,你的应用也可以根据你的设置定期执行任务
使用
1.在build.gradle中引入
dependencies {
...
implementation 'com.evernote:android-job:1.2.6'
}
2.新建类继承自Job,重写其onRunJob方法,并在其中编写你想要执行的任务
public class ShowNotificationJob extends Job {
public static final String TAG = "show_notification_job";
@NonNull
@Override
protected Result onRunJob(@NonNull Params params) {
PendingIntent pi = PendingIntent.getActivity(getContext(),0,new Intent(getContext(),MainActivity.class),0);
Notification notification = new NotificationCompat.Builder(getContext())
.setContentTitle("Android Job Demo")
.setContentText("Notification from Android Job Demo App.")
.setAutoCancel(true)
.setContentIntent(pi)
.setSmallIcon(R.mipmap.ic_launcher)
.setShowWhen(true)
.setColor(Color.RED)
.setLocalOnly(true)
.build();
NotificationManagerCompat.from(getContext())
.notify(new Random().nextInt(), notification);
return Result.SUCCESS;
}
}
3.新建JobRequest(将Job中的tag传入,作为唯一标识),在其中设置任务执行的条件(比如充电状态下,不同的网络状态下,何时执行...),最后不要忘记build和schedule一下
new JobRequest.Builder(ShowNotificationJob.TAG)
.setPeriodic(TimeUnit.SECONDS.toMillis(900), TimeUnit.SECONDS.toMillis(300))
.setUpdateCurrent(true)
.build()
.schedule();
4.新建类继承自JobCreator,重写create方法,根据JobRequest传入的tag决定新建哪一个Job的实例
public class DemoJobCreater implements JobCreator {
@Nullable
@Override
public Job create(@NonNull String tag) {
switch (tag) {
case ShowNotificationJob.TAG:
return new ShowNotificationJob();
default:
return null;
}
}
}
5.在MainActivity中新建JobManager,并将新建的Creator添加进去
JobManager.create(this).addJobCreator(new DemoJobCreater());
项目结构