Android-job

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());

项目结构
image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值