android中定时任务的两种实现

目前有两种方式参考:

1、使用AlarmManager,reboot之后定时任务被清除

如:

        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(Constant.ServiceName);
        intent.putExtra("action", action);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        long triggerAtMillis = SystemClock.elapsedRealtime();
        long intervalMillis = 2 * 60 * 60 * 1000; // 2 hour
        manager.setRepeating(AlarmManager.ELAPSED_REALTIME, triggerAtMillis, intervalMillis, pendingIntent);

2、5.0以后可使用JobSheduler,用JobInfo.Builder生成JobInfo加到JobSheduler中,具体任务的执行逻辑需要继承实现JobService

     JobInfo.Builder(int jobId, ComponentName jobService)方法将JobInfo和Jobservice关联。生成JobInfo是可以设置执行条件,比如:网络,系统是否空闲,是否充电等。

     与AlarmManager有一个不同是JobSheduler机制可以通过调用JobInfo.Builder.setPersisted(boolean isPersisted)设置当手机重启后任务也不会被清除。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值