我正在构建一个提醒应用程序,应该能够设置多个提醒。我有一个AddNewReminder底部工作表视图,它有一个editText输入提醒名称,一个数据交换对话框,一个时间选择对话框和一个保存按钮,它将数据保存到SQLite数据库并设置提醒。
AddNewReminder.java (保存按钮的OnClickListener) :-
String name = mReminderNameInsert.getText().toString();
id = new Random().nextInt(100);
Intent reminderReciever = new Intent(getContext(), ReminderReceiver.class);
reminderReciever.putExtra("reminderName", name)
.putExtra("id", id);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, reminderReciever, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, ih);
calendar.set(Calendar.MINUTE, imin);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.DAY_OF_MONTH, iday);
calendar.set(Calendar.MONTH, imon);
long lTime = calendar.getTimeInMillis();
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
manager.setExact(AlarmManager.RTC_WAKEUP, lTime, pendingIntent);然后使用广播接收器显示通知。
String mReminderName;
String CHANNEL_ID = "channel";
int id;
@Override
public void onReceive(Context context, Intent intent) {
mReminderName = intent.getStringExtra("reminderName");
id = intent.getIntExtra("id", 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel("id", "name", NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = context.getSystemService(NotificationManager.class);
manager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "id");
mBuilder.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle("It's Time..!!")
.setContentText(mReminderName + "" + id)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true);
NotificationManagerCompat compat = NotificationManagerCompat.from(context);
compat.notify(id, mBuilder.build());
}将显示提醒通知,但只显示最新的通知。(就像我设置了两个提醒,一个是8:30,另一个是8:31,只有8:31的提醒显示为通知)。
我应该将警报管理器代码添加到MainActivity而不是AddNewReminder片段中吗?
任何帮助都将非常感谢。
发布于 2021-01-16 05:33:37
您在这两种情况下使用的PendingIntent,一个用于8:30的警报,另一个用于8:31的警报,代表同一个对象,因此调用cancel()来删除旧的对象。正如官方文件提到的,
人们犯的一个常见错误是创建多个意图仅在“额外”内容中有所变化的PendingIntent对象,期望每次得到不同的PendingIntent。如果您确实需要同时活动的多个不同的PendingIntent对象(例如用作两个同时显示的通知),则需要确保它们与不同的PendingIntents相关联。这可能是Intent#filterEquals(意图)考虑的任意意图属性,也可能是提供给PendingIntents的不同请求代码整数。
所以试试下面的方法。
Intent reminderReciever = new Intent(getContext(), ReminderReceiver.class);
reminderReciever.putExtra("reminderName", name);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), id, reminderReciever, 0);https://stackoverflow.com/questions/65745796
复制相似问题