Уведомление о нескольких тревогах одновременно

Мое приложение должно отображать уведомление о тревоге всякий раз, когда пришло время принимать таблетки. Если нужно принять две таблетки одновременно, то появятся два уведомления. Прямо сейчас мое приложение может отображать отдельные уведомления, если время приема таблеток отличается. Проблема в том, что если они находятся одновременно, отображается только последний.

Я пробовал некоторые решения из StackOverflow. но что-то не работает для меня.

....................
    Intent intent = new Intent(AddReminder.this, LocalNotification.class);
                AlarmManager alm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

      int id = dbHelper.getAlarmCount() + 1;
     dbHelper.addToLocalNotification(id, dateStr, getResources().getString(R.string.reminder), descp,
                            param,"");
                    intent.putExtra("title",getResources().getString(R.string.reminder));
                    intent.putExtra("desc",descp);
                    PendingIntent pi = PendingIntent.getBroadcast(
                            getApplicationContext(), id, intent, 0);
                    setAlarmValue(alm,dateStr,pi);
.....................................................

    private void setAlarmValue(AlarmManager alm, String date, PendingIntent pi){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            try {
                Date dateVal = sdf.parse(date);
                String repeat = s1.get(weiderholen.getSelectedItemPosition()).toLowerCase();

                if (repeat.equals("daily")) {
                    alm.setRepeating(AlarmManager.RTC_WAKEUP, dateVal.getTime(), AlarmManager.INTERVAL_DAY, pi);
                } else if (repeat.equals("weekly")) {
                    alm.setRepeating(AlarmManager.RTC_WAKEUP, dateVal.getTime(), AlarmManager.INTERVAL_DAY * 7, pi);
                } else if (repeat.equals("monthly")) {
                    alm.setRepeating(AlarmManager.RTC_WAKEUP, dateVal.getTime(), AlarmManager.INTERVAL_DAY * 30, pi);
                } else if (repeat.equals("yearly")) {
                    alm.setRepeating(AlarmManager.RTC_WAKEUP, dateVal.getTime(), AlarmManager.INTERVAL_DAY * 365, pi);
                } else {
                    alm.set(AlarmManager.RTC_WAKEUP, dateVal.getTime(), pi);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

и мой вещательный приемник

public class LocalNotification extends BroadcastReceiver {
    int m;
    public void onReceive(Context context, Intent intent) {
        m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);

        NotificationManager mNotificationManager;

        Notification notification = getNotification(context,intent.getStringExtra("title"),intent.getStringExtra("desc"));


        mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            /* Create or update. */
            NotificationChannel channel = new NotificationChannel("my_channel_01",
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            mNotificationManager.createNotificationChannel(channel);
        }
        mNotificationManager.notify(m, notification);


    }

    @TargetApi(Build.VERSION_CODES.O)
    public Notification getNotification(Context context, String title, String message){
        long when = System.currentTimeMillis();
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
//        Intent viewIntent = new Intent(context, DashBoardActivity.class);
        Intent viewIntent = new Intent(context, SplashActivity.class);
        viewIntent.putExtra("TRIGGERED_FROM", "NOTIFICATION_TASK");
        PendingIntent pendingIntent = PendingIntent.getActivity(context, m, viewIntent, PendingIntent.FLAG_ONE_SHOT);



        Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,"my_channel_01")
                .setSmallIcon(R.mipmap.applogo)
                .setContentTitle(title)
                .setContentText(message).setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent);

        Notification notification = mBuilder.build();
        notification.flags=Notification.FLAG_AUTO_CANCEL;
        return notification;
    }

}

person Mohammed Faiz    schedule 02.09.2019    source источник
comment
Если нужно принять две таблетки одновременно, то должны появиться два уведомления... Почему бы просто не показать 1 уведомление с 2 сообщениями?   -  person B001ᛦ    schedule 02.09.2019
comment
@ B001ᛦ, потому что это сложно, потому что напоминания повторяются. некоторые болезни могут быть ежедневными, а некоторые еженедельными   -  person Mohammed Faiz    schedule 02.09.2019


Ответы (1)


проблема в mNotificationManager.notify(m, notification);. m одинаково для уведомления в одно и то же время, поэтому создайте статический идентификатор уведомления, который будет обновляться в методе onReceive.

Выше метод onReceive

 `private static int NOTIFICATION_ID = 1; `

В вашем onReceive увеличивается этот идентификатор

NOTIFICATION_ID++

Затем передайте этот идентификатор

mNotificationManager.notify(NOTIFICATION_ID, notification);

Надеюсь, что это работает! :)

person M.AQIB    schedule 02.09.2019
comment
m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE); значение «m» отличается для каждого уведомления. но не работает. - person Mohammed Faiz; 02.09.2019
comment
Это правильный ответ. Большое спасибо - person Bianca Balan; 02.06.2021