Nano Hash - криптовалюты, майнинг, программирование

Как я могу прикрепить несколько дополнений к намерению в пакетном уведомлении?

Я получаю несколько уведомлений, каждое со своим уникальным идентификатором.

Желательно, чтобы для каждого уведомления было собственное дополнение.

Но когда я сохраняю/сохраняю уведомления в объекте Bundle, всем уведомлениям назначается один и тот же дополнительный -(т. е. дополнение, которое принадлежит к последнему уведомлению).

Я подтвердил это, потому что, когда я нажимаю на любое уведомление, я перехожу к последнему сообщению, которое я получил.

Хотя я хочу, чтобы меня отправили в сообщение, соответствующее уведомлению, я только что нажал.

Ниже приведен соответствующий фрагмент кода: -

 public void createNotif(Poste poste, Comment comment, Boolean checkGroupSon) {

    if (comment == null) {
        emeteur = poste.getEmmet();
        message = poste.getTx();
        pathImg = poste.getImg();
    } else {
        emeteur = comment.getEmmet();
        message = comment.getComment();
        pathImg = comment.getImage();
    }
    //onDismiss Intent
    Intent intent = new Intent(mContext, NotificationControllerReceiver.class);
    PendingIntent mBroadcastIntentController = PendingIntent.getBroadcast(mContext, 0, intent, 0);


    Intent notificationIntent = new Intent(mContext, CommentPhotoActivity.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Intent.FLAG_ACTIVITY_CLEAR_TASK|
    notificationIntent.putExtra("pid", poste.getId());


    PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    //TEST    notification.setLatestEventInfo(getApplicationContext(), "YuYu", "Vous avez reçu un nouveau poste", contentIntent);
    //TEST  notification.flags = Notification.FLAG_AUTO_CANCEL;

    //TEST
    //    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext()).setContentTitle("Poste: "+emeteur).setSmallIcon(R.drawable.ic_launcher).setContentIntent(contentIntent).setContentText(message).setDeleteIntent(mBroadcastIntentController).setPriority(Notification.PRIORITY_MAX);
    NotificationCompat.Builder notificationBuilder = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        notificationBuilder = new NotificationCompat.Builder(mContext, "poste");


            if (pathImg == null)
                notificationBuilder.setContentTitle(emeteur).setSmallIcon(R.drawable.ic_launcher).setContentIntent(contentIntent).setContentText(emeteur + ": " + message).setDeleteIntent(mBroadcastIntentController).setPriority(NotificationCompat.PRIORITY_MAX);
            else
                notificationBuilder.setContentTitle(emeteur).setSmallIcon(R.drawable.ic_launcher).setContentIntent(contentIntent).setContentText(emeteur + ": Photo \uD83D\uDCF7 " + message).setDeleteIntent(mBroadcastIntentController).setPriority(NotificationCompat.PRIORITY_MAX);


        }

        //  notificationBuilder.setContentTitle("Poste: "+emeteur).setSmallIcon(R.drawable.ic_launcher).setContentIntent(contentIntent).setContentText(message).setDeleteIntent(mBroadcastIntentController).setPriority(Notification.PRIORITY_MAX);
    } 
    //  long[] v = {500,1000};
    // notificationBuilder.setVibrate(v);
    notifications = null;
    boolean b = notifHashMap.containsKey(poste.getId());
    if (b) {

        notifications = notifHashMap.get(poste.getId());
        // Add your All messages here or use Loop to generate messages
        if (pathImg == null)
            notifications.add(emeteur + ":" + message);
        else
            notifications.add(emeteur + ": Photo \uD83D\uDCF7 " + message);

        notifHashMap.put(poste.getId(), notifications);
    } else {
        notifications = new ArrayList<String>();
        // Add your All messages here or use Loop to generate messages
        if (pathImg == null)
            notifications.add(emeteur + ":" + message);
        else
            notifications.add(emeteur + ": Photo \uD83D\uDCF7 " + message);

        notifHashMap.put(poste.getId(), notifications);
    }


    //  if (inboxStyle == null)
    //    inboxStyle = new NotificationCompat.InboxStyle();
    //else
    inboxStyle = new NotificationCompat.InboxStyle(notificationBuilder);
    if (notifications.size() > 1) {
        if (poste.getImg() == null)
            inboxStyle.setBigContentTitle("Poste:" + poste.getTx());
        else
            inboxStyle.setBigContentTitle("Poste: \uD83D\uDCF7 " + poste.getTx());

        inboxStyle.setSummaryText("Vous avez " + notifications.size() + " notifications.");
        for (int i = 0; i < notifications.size(); i++) {
            inboxStyle.addLine(notifications.get(i));
        }
    } else if (notifications.size() == 1) {
        inboxStyle.addLine(notifications.get(0));
    }

    notificationBuilder.setStyle(inboxStyle);
    notificationBuilder.setVibrate(new long[]{0L});
    //notificationBuilder.setNumber(value++);
    if (!checkGroupSon) {
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        notificationBuilder.setSound(alarmSound);
    }


    NotifManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                             /* Create or update. */
        mChannel = new NotificationChannel("poste", "YuYu", NotificationManager.IMPORTANCE_LOW);
        mChannel.enableLights(true);
        mChannel.setLightColor(Color.RED);
        mChannel.canShowBadge();
        mChannel.setVibrationPattern(new long[]{ 0 });
        mChannel.enableVibration(true);
      /*  if (!checkGroupSon) {
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        } */
        assert NotifManager != null;
        notificationBuilder.setChannelId("poste");
       // NotifManager.deleteNotificationChannel("poste");
        NotifManager.createNotificationChannel(mChannel);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        summaryNotification = new NotificationCompat.Builder(mContext, "poste")
                .setSmallIcon(R.drawable.ic_launcher)
                .setStyle(new NotificationCompat.InboxStyle()
                        .addLine("1")
                        .addLine("2")
                        .setBigContentTitle("nouveau messages")
                        .setSummaryText("Nouveau message"))
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setGroup("example_group")
                .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN)
                .setGroupSummary(true).build();
    }

    Notification notification = notificationBuilder.setGroup("example_group").build();

    notification.flags = Notification.FLAG_AUTO_CANCEL;

    // assert  NotifPostMsgManager != null;
    //TEST   manager.notify(ID_NOTIFICATION, notification);
    NotifManager.notify(poste.getId(), notification);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        NotifManager.notify(1, summaryNotification);
}

  • В чем вопрос? 11.02.2019
  • Как мне это сделать: при нажатии на любое уведомление в группе уведомлений я захожу в соответствующий этому уведомлению пост. 11.02.2019
  • Спасибо за исправление 11.02.2019
  • Привет @ m0skit0 у тебя есть решение? 12.02.2019
  • Пожалуйста, не спамьте мое имя. Если бы у меня было решение, я бы вам ответил. Отсутствие ответа означает отсутствие решения, извините. 12.02.2019
  • Извините, если спамлю ваше имя 12.02.2019

Ответы:


1

вы используете один и тот же идентификатор в своем NotifManager.notify(1, summaryNotification) //id == 1, поэтому вы получаете тот же результат намерения, вы должны использовать другой идентификатор, и он должен храниться в некоторых сохраненных данных как sharedPreferences

12.02.2019
  • Я нашел решение, PendingIntent обновляет данные до последней версии, и мы используем requestCode как 0 для каждого из PendingIntent. Таким образом, он возвращает только последние данные. Нам нужно установить другой код запроса для каждого уведомления. 12.02.2019
  • Точно мой друг 12.02.2019
  • Новые материалы

    Кластеризация: более глубокий взгляд
    Кластеризация — это метод обучения без учителя, в котором мы пытаемся найти группы в наборе данных на основе некоторых известных или неизвестных свойств, которые могут существовать. Независимо от..

    Как написать эффективное резюме
    Предложения по дизайну и макету, чтобы представить себя профессионально Вам не позвонили на собеседование после того, как вы несколько раз подали заявку на работу своей мечты? У вас может..

    Частный метод Python: улучшение инкапсуляции и безопасности
    Введение Python — универсальный и мощный язык программирования, известный своей простотой и удобством использования. Одной из ключевых особенностей, отличающих Python от других языков, является..

    Как я автоматизирую тестирование с помощью Jest
    Шутка для победы, когда дело касается автоматизации тестирования Одной очень важной частью разработки программного обеспечения является автоматизация тестирования, поскольку она создает..

    Работа с векторными символическими архитектурами, часть 4 (искусственный интеллект)
    Hyperseed: неконтролируемое обучение с векторными символическими архитектурами (arXiv) Автор: Евгений Осипов , Сачин Кахавала , Диланта Хапутантри , Тимал Кемпития , Дасвин Де Сильва ,..

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

    Обеспечение масштабируемости LLM: облачный анализ с помощью AWS Fargate и Copilot
    В динамичной области искусственного интеллекта все большее распространение получают модели больших языков (LLM). Они жизненно важны для различных приложений, таких как интеллектуальные..