5

我正在尝试在 android 中设置一个重复警报,最终将在用户指定的时间响起。然而,一旦设置了闹钟,它就会立即响起,即使我确保在设置闹钟之前不会响起闹钟。例如,我将下面的代码设置为在 10:43 发出警报,所以我将警报设置为 10:41,但警报立即响起。有任何想法吗?提前致谢。

    public class Alarm extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();


        Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For

        Intent scheduledIntent = new Intent(context,ReminderMessage.class);
        scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(scheduledIntent);
        // example

        wl.release();
    }

    public void SetAlarm(Context context) {
        AlarmManager am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);

        Date dat = new Date();
        Calendar cal_alarm = Calendar.getInstance();
        Calendar cal_now = Calendar.getInstance();
        cal_now.setTime(dat);
        cal_alarm.setTime(dat);
        cal_alarm.set(Calendar.HOUR_OF_DAY, 10);
        cal_alarm.set(Calendar.MINUTE, 43);
        cal_alarm.set(Calendar.SECOND, 0);

        if(cal_alarm.before(cal_now)){
            cal_alarm.add(Calendar.DATE, 1);
        }


        Intent i = new Intent(context, Alarm.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), cal_alarm.getTimeInMillis() , pi); // Millisec * Second * Minute
    }

    public void CancelAlarm(Context context) {
        Intent intent = new Intent(context, Alarm.class);
        PendingIntent sender = PendingIntent
                .getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }
}
4

1 回答 1

9

我认为你的线路:

am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), cal_alarm.getTimeInMillis() , pi); // Millisec * Second * Minute

是立即触发警报,第二个参数是预定时间,第三个是周期。所以如果你想让你的闹钟在 cal_alarm 时间响起,你想使用类似的东西:

am.setRepeating(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), 1000*60*5 , pi); // Millisec * Second * Minute

这应该在 cal_alarm 时间响起,并每 5 分钟重复一次。

AlarmManager.SetRepeating API 文档

于 2012-10-18T15:10:40.980 回答