在特定时间在 android 工作室中创建每日通知,但每当我运行该应用程序时它都会出现



我把这段代码放在OnCreate中,有两个版本来设置日历和日期的时间

我已经使用 alaramManager 和通知管理器创建了通知代码,并调用 pendingIntended 方法在特定时间获取通知,但每当我运行该应用程序时,我都会收到通知。

Calendar calendar = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
calendar = getInstance();
calendar.set(HOUR_OF_DAY,hour);
calendar.set(MINUTE,min);
}else{
date = new Date();
date.setHours(hour);
date.setMinutes(min);
}
Intent intent = new Intent(getApplicationContext(),Notification_reciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),uniquecode,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}else{
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,date.getTime() ,AlarmManager.INTERVAL_DAY,pendingIntent);
}
}

我的通知收件人是这个

类 Notification_reciever 扩展了 BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context,MainActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent1 =PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent2 =PendingIntent.getActivity(context,102,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder1 = new NotificationCompat.Builder(context);
builder1.setContentIntent(pendingIntent1);
builder1.setSmallIcon(R.drawable.plan);
builder1.setContentTitle("Night Notification");
builder1.setContentText("Plan Tommorow");
builder1.setAutoCancel(true);
notificationManager.notify(100,builder1.build());

} }

如果您在onCreate()中设置该代码,则每次打开应用程序时它都会运行。 只要您将闹钟设置为当天晚些时候的某个时间(例如,下午 5:00 并且您将其设置为下午 5:00 到晚上 11:59 之间的任何时间),当前一切应该都可以正常工作。

但是,导致警报在打开后立即触发的问题可能是由于将警报设置为当天已经过去了的时间,这始终会导致警报立即触发 - 例如,如果是下午 5:00 并且您尝试将闹钟设置为下午 1:30,它不会在明天下午 1:30 触发,而是会立即触发。

要解决此问题,您需要检查当天所需的闹钟时间是否已经过去了,如果它已将一天添加到您的日历对象上,以便明天而不是立即触发。

下面的代码片段检查您设置的日历时间是否已经过去了,如果已经过了,则添加一天,以便明天正确触发。

if(calendar.before(System.currentTimeMillis())){
calendar.set(Calendar.DATE, 1);
}

所以你的代码应该看起来像这样:

Calendar calendar = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
calendar = getInstance();
calendar.set(HOUR_OF_DAY,hour);
calendar.set(MINUTE,min);
if(calendar.before(System.currentTimeMillis())){
calendar.set(Calendar.DATE, 1);
}
}else{
date = new Date();
date.setHours(hour);
date.setMinutes(min);
}

我不确定您为什么将Date用于 Nougat 下的任何东西,我已经成功地将Calendar用于低至 4.x 的设备AlarmManager次,但是如果您出于某种原因需要它,那么您应该能够同时检查它并添加相当于calendar.set(Calendar.DATE, 1);的等效物。

相关内容

最新更新