Alarmmanager设置定时任务有延迟的问题

安卓在6.0引入了新的省电机制——Doze模式,系统息屏后会把一些广播啊网络啊什么的都切断或者降低频率,所有我们设的闹钟广播也被延迟了,在android6.0之后,如果想继续保持Alarm在手机处于所谓Doze模式时仍然能够被即时响应,则需要使用AlarmManager新提供的两个方法setAndAllowWhileIdle()或者setExactAndAllowWhileIdle()

最后代码这样写:

AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(action);
    PendingIntent pendIntent = PendingIntent.getBroadcast(getApplicationContext(),requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
    {       
        alarmMgr.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendIntent);
    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
         alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendIntent);
    }else{
         alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendIntent);
    }

如果你是要设置重复的闹钟,比如每天七点做一个什么任务,之前是用

manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, sender);

现在应该用

manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, sender;

但是好像还是有一分钟左右延迟,无奈!

你可能感兴趣的:(Alarmmanager设置定时任务有延迟的问题)