Установить несколько будильников в Android Studio - PullRequest
0 голосов
/ 09 апреля 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 Ответ

0 голосов
/ 09 апреля 2020

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

notificationManager.notify(1, notification);

См. Также "Показать уведомление" из руководства по уведомлениям

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

AlarmReceiver вызывается какой-то другой компонент. Этот компонент может поставить некоторый флаг как дополнительный для Intent, который используется для трансляции. Тогда вы можете оценить Intent дополнительно в onReceive()

...