Android 在一天的特定时间使用 AlarmManager 每天重复通知

标签 android alarmmanager

我需要 Android 应用程序在每天早上 8 点、下午 3 点和晚上 8 点发送通知来提醒用户。因此,当应用程序启动时,我在 MainActivity 的 onCreate() 中使用以下三行。但是,当我运行该应用程序时,所有三个通知都会同时出现,而不是在需要的时间出现。

    setRepeatedNotification(1,8,0,0); 
    setRepeatedNotification(2,15,0,0); 
    setRepeatedNotification(3,20,0,0);    

这是为什么呢?我还在此处附加了 setRepeatedNotification 函数。谢谢!

private void setRepeatedNotification(int ID, int hh, int mm, int ss) {
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, ID, alarmIntent, 0);

    Calendar calendar = Calendar.getInstance();
   // calendar.set();
    calendar.set(Calendar.HOUR_OF_DAY, hh);
    calendar.set(Calendar.MINUTE, mm);
    calendar.set(Calendar.SECOND, ss);

    // Clear previous everyday pending intent if exists.
    if (null != mEverydayPendingIntent) {
        alarmManager.cancel(mEverydayPendingIntent);
    }
    mEverydayPendingIntent = pendingIntent;
    alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mEverydayPendingIntent);
}

最佳答案

这是更新后的代码:

private void setRepeatedNotification(int ID, int hh, int mm, int ss) {
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent alarmIntent = new Intent(StartActivity.this, AlarmReceiver.class);
    alarmIntent.putExtra("ID",ID);
    Log.d("setRepeatedNotification", "ID:" + ID);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(StartActivity.this, ID, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar calendar = Calendar.getInstance();
    Calendar now = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, hh);
    calendar.set(Calendar.MINUTE, mm);
    calendar.set(Calendar.SECOND, ss);

    //check whether the time is earlier than current time. If so, set it to tomorrow. Otherwise, all alarms for earlier time will fire

    if(calendar.before(now)){
        calendar.add(Calendar.DATE, 1);
    }

    mEverydayPendingIntent = pendingIntent;
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mEverydayPendingIntent);



}

关于Android 在一天的特定时间使用 AlarmManager 每天重复通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30128846/

相关文章:

android - 警报管理器运行 Activity

android - 在安卓 Lollipop 上创建闹钟

android - Google (Play) sleep 模式下的位置服务更新间隔变化 (Android)

android.hardware.Camera$EventHandler.handleMessage

android - Observable.interval() 与 initialDelay

android - 作为业务需求,我必须让我的后台服务在我的 android 应用程序中始终运行

android - 如何调试您的应用程序正在运行哪些 AlarmManager 警报?

带有自定义适配器的 Android ListView 仅显示最后一项

android - 在添加Fabric的崩溃报告后,我无法在gradle中添加新的库

android - 我如何判断我的 Activity 是否由广播接收器启动?