android中定时任务的两种实现

时间:2021-05-18 07:51:17

目前有两种方式参考:

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)设置当手机重启后任务也不会被清除。