我必须在早上5:30触发本地通知,这是有效的。但问题是每当我打开我的应用程序时,通知也会被触发。这是我MainActivity
中的代码:
在onCreate()
的{{1}}中:
MainActivity
这是我的alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(this, MyStartServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 5);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
:
MyStartServiceReceiver
为什么每次打开我的应用程序时都会触发它?
答案 0 :(得分:2)
因为你创造了
Calendar.getInstance()
例如在上午9点,但是在过去的时间上午5:30设定。所以当你使用
时alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
它已经发生了。
您可以使用此
if(calendar.getTimeInMillis() < System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
答案 1 :(得分:2)
您正在设置闹钟当前日期上午5:05,如果已经通过警报将立即触发。要阻止它,请这样做。
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(this, MyStartServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 5);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
alarmManager.cancel(pendingIntent);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
我们在这里做的是,如果时间已经过去,我们将日期添加+1,这样它将从下一个日期开始,我们将取消之前的设置警报。
答案 2 :(得分:0)
试试这个
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(this, MyStartServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
if(calendar.getTime().after(new Date())){
calendar.set(Calendar.Date,1);
}
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);