gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:39:28 26 4
gpt4 key购买 nike

我需要 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com