警报管理器无法正常工作

时间:2016-04-12 06:06:27

标签: android alarmmanager

警报管理器无法正常工作,因为有时它会在很长时间内触发警报,但有时它会在2-5分钟的延迟时间后触发警报,有时甚至不会触发警报

public static void setAlarmTime(Context context, String userName, String selectedRitual,int dayOfWeek, int hourOfDay, int minute, int rStamp, boolean isUpdate) 
 {
     Calendar now = Calendar.getInstance();
     Calendar cal = Calendar.getInstance();
     cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
     cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
     cal.set(Calendar.MINUTE, minute);
     cal.set(Calendar.SECOND, 0);
     cal.set(Calendar.MILLISECOND, 0);

     long alarmTime = cal.getTimeInMillis();

    Intent intent= new Intent(context, AlarmReceiver.class);
    intent.putExtra(AppsConstant.SELECTED_RITUAL, selectedRitual);
    intent.putExtra(AppsConstant.user_name, userName);
    intent.putExtra("alarmTime", "day"+dayOfWeek+" hour"+hourOfDay+":"+minute);
    PendingIntent alarmIntent;
    if(!isUpdate)
        alarmIntent = PendingIntent.getBroadcast(context.getApplicationContext(), rStamp, intent, 0/*PendingIntent.FLAG_UPDATE_CURRENT*/);
    else
        alarmIntent = PendingIntent.getBroadcast(context.getApplicationContext(), rStamp, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager=(AlarmManager)context.getSystemService(context.ALARM_SERVICE);

  //check whether the time is earlier than current time. 
    if(cal.before(now))
    {
        alarmTime = cal.getTimeInMillis()+(alarmManager.INTERVAL_DAY * 7);
    }
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmTime, AlarmManager.INTERVAL_DAY * 7, alarmIntent);
 }

1 个答案:

答案 0 :(得分:0)

您正在使用setInexactRepeating(),根据文档,它并不总是在给定时间内触发:

  

安排具有不准确触发时间要求的重复警报;   例如,每小时重复一次的警报,但不一定是   每小时的最高点。

如果您认为它根本不会触发,请考虑在某些情况下您可能会重新安排现有警报。