警报管理器延迟警报振铃的问题

时间:2019-03-26 13:52:54

标签: android android-layout timepicker android-timepicker

我遇到了一个问题,当我设置时间时,闹钟响了一段时间。有时警报也会提前响起。我不确定我做错了什么。希望有人可以帮助我解决这个问题。

public void showHourPicker(View view) {


    currentHour = calendar.get(Calendar.HOUR_OF_DAY);
    currentMinute = calendar.get(Calendar.MINUTE);

    timePickerDialog = new TimePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int hourOfDay, int minutes) {

            if (hourOfDay >= 12) {
                amPm = "PM";
            } else {
                amPm = "AM";
            }
            txtTime.setText(String.format("%02d:%02d ", hourOfDay, minutes) + amPm);

            calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
            calendar.set(Calendar.MINUTE,minutes);
        }

    }, currentHour, currentMinute, false);

    timePickerDialog.setTitle(" Your Expected Time : " + exp.getText());
    timePickerDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    timePickerDialog.show();

    startAlarm(calendar);

}

public void startAlarm(Calendar calendar) {

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, MyBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

}

2 个答案:

答案 0 :(得分:0)

这是AlarmManager.setRepeating中所述的预期行为:

  

从API 19开始,所有重复警报都是不精确的。如果您的应用程序需要精确的交付时间,则它必须使用一次精确的警报,并如上所述每次重新安排。

答案 1 :(得分:0)

setRepeating 等于 API 19 之上的 setInexactRepeating。如果您想在固定间隔后准确地重复它,请在您的广播接收器中使用 handler.postDelayed。我附上了一个具有相同实现的广播接收器代码

public class AlertReceiver extends BroadcastReceiver {
private MediaPlayer alarmRinger;
@Override
public void onReceive(Context context, Intent alarmIntent) {
   alarmRinger = MediaPlayer.create(context, R.raw.alarmringer);
   runnable.run();
   }
private final Handler handler = new Handler();
private final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        alarmRinger.start();
        handler.postDelayed(this, 3600000);//Change the timing accordingly in MS 
    }
};

}

这里我的 AlarmManager 触发广播接收器,然后广播接收器触发 MediaPlayer 以创建用于播放声音的媒体播放器,并触发 runnable.run() 导致 Runnable 运行.当 runnable 被触发时,mediaPlayer 运行并播放声音,然后 handler.postDelayed 被设置为在 1 小时(3600000 毫秒)内再次重复 Runnable 的任务,这会无限重复或直到你杀死 runnable。< /p>