Второе уведомление отменяет первое - Android Studio - PullRequest
0 голосов
/ 03 апреля 2020

Я пытаюсь управлять двумя отдельными уведомлениями в моем проекте. У меня есть уведомление, которое отправляется пользователю, когда должен быть выставлен счет, и уведомление, которое отправляется, когда платеж успешен.

Когда я вызываю уведомление из моего класса AlarmReceiver, вызывается уведомление о платеже, даже для счета необходимо уведомление. Я думаю, это потому, что он вызывается последним в OnReceive, и поэтому отменяется, уведомление о счете подлежит оплате.

Существует ли тип оператора if или switch, который я могу вставить в свой OnReceive, чтобы увидеть проверку какой код запроса был вызван (101 или 102), а затем вызвать это уведомление?

Вот мой код:

public class AlarmReceiver extends BroadcastReceiver {

    private static final String CHANNEL_ID = "bills.channelId";


    /**
     * @param context
     * @param intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {

        // run notification 1
        userHasBill(context, intent);
        // run notification 2
        userPaymentIsSuccessful(context, intent);


    }

    /**
     * Notification to call when the user sets a reminder
     * @param intent
     */
    public void userHasBill(Context context, Intent intent) {

        Intent notificationIntent = new Intent(context, MainMenuActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(EmailActivity.class);
        stackBuilder.addNextIntent(notificationIntent);

        PendingIntent pendingIntent = stackBuilder.getPendingIntent(101, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder = new Notification.Builder(context);

        // Notification Builder and setting parameters?
        Notification notification = builder.setContentTitle("Bill Reminder!")
                .setContentText("Just a reminder that you have a bill due!")
                .setTicker("Just a reminder that you have a bill due!")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent).build();


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(CHANNEL_ID);
        }

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "bills",
                    IMPORTANCE_DEFAULT
            );
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(1, notification);


    }


    /**
     * Notification to call when bill payment is successful
     *
     * @param context current context
     * @param intent  intent to go to home activity
     */
    public void userPaymentIsSuccessful(Context context, Intent intent) {

        Intent notificationIntent = new Intent(context, MainMenuActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(EmailActivity.class);
        stackBuilder.addNextIntent(notificationIntent);

        PendingIntent pendingIntent = stackBuilder.getPendingIntent(102, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder = new Notification.Builder(context);

        Notification notification = builder.setContentTitle("Payment successful!")
                .setContentText("Your payment was successful!")
                .setTicker("Your Payment was Successful!")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent).build();


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(CHANNEL_ID);
        }

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "bills",
                    IMPORTANCE_DEFAULT
            );
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(1, notification);


    }


}

Я уже пытался сделать два идентификатора канала, но он по-прежнему вызывает второе уведомление, которое находится в OnReceive

1 Ответ

1 голос
/ 03 апреля 2020

Вы публикуете два уведомления с одинаковым идентификатором (равно 1). Эти идентификаторы должны быть уникальными для разных уведомлений.

NotificationManager.notify ()

publi c void notify (int id, Notificationtification).
Опубликуйте уведомление для отображения в строке состояния. Если ваше приложение уже опубликовало уведомление с таким же идентификатором и еще не было отменено, оно будет заменено обновленной информацией.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...