Как я могу очистить предыдущую активность, которая открыта из крана на уведомлении в Android? - PullRequest
1 голос
/ 21 октября 2019

Есть приложение для напоминания. Сейчас пользователи создали 5 напоминаний. R1, R2, R3, R4, R5.

И для всех напоминаний время одинаковое. Так что все напоминания пришли в одно и то же время. Теперь я нажимаю на уведомление, которое является R1. и когда я нажимаю, он открывает определенное действие и показывает в соответствии с деталями, потому что я отправил идентификатор этого напоминания намеренно.

Теперь я нажимаю на R2 / R3 / R4 / R5, это открывает детали в соответствии с R1только вместо R2 / R3 / R4 / R5.

Примечание. В onReceive я создаю уведомление от этого. Кроме того, для всех напоминаний я открываю одно и то же действие, но детали этого действия должны отличаться в зависимости от идентификатора напоминания. Кроме того, когда я отправляю ReminderId / mReceivedId с намерением, это правильно , а не то же самое.

Код:

editIntent = new Intent(context, ReminderDetailActivity.class);
editIntent.putExtra(REMINDER_ID, mReceivedId);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(context, rowId, editIntent, 0);

Полный код (я вызываю createNotification ()от onReceive):

private void createNotification() {
    int rowId = getRowId(mReceivedId);
    Uri mUri;
    if (preferenceManager.getRingtoneUri() != null) {
        mUri = Uri.parse(preferenceManager.getRingtoneUri());
    } else {
        mUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    }
    String mTitle = reminder.getTitle();
    String id = "1";
    PendingIntent pendingIntent;
    NotificationCompat.Builder builder;
    if (mNotificationManager == null) {
        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }
    Intent editIntent;
    if (SDK_INT >= Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        assert mNotificationManager != null;
        NotificationChannel mChannel = mNotificationManager.getNotificationChannel(id);
        if (mChannel == null) {
            mChannel = new NotificationChannel(id, mTitle, importance);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);
        }
        builder = new NotificationCompat.Builder(context, id);
        editIntent = new Intent(context, ReminderDetailActivity.class);
        editIntent.putExtra(REMINDER_ID, mReceivedId);
        editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pendingIntent = PendingIntent.getActivity(context, rowId, editIntent, 0);
        builder.setContentTitle(mTitle)

                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .setContentTitle(mTitle)
                .setSmallIcon(R.drawable.ic_alarm_black_24dp)
                .setSound(mUri)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setCategory(NotificationCompat.CATEGORY_REMINDER)
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("Have you completed your task?"))
                .setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE)
                .addAction(R.drawable.ic_icon_alarm, context.getString(R.string.pay_now), pendingIntent);
        builder.setColor(ContextCompat.getColor(context, R.color.colorPrimary));


    } else {
        builder = new NotificationCompat.Builder(context, id);
        editIntent = new Intent(context, ReminderDetailActivity.class);
        editIntent.putExtra(REMINDER_ID, mReceivedId);
        editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pendingIntent = PendingIntent.getActivity(context, rowId, editIntent, 0);
        builder.setContentTitle(mTitle)

                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .setContentTitle(mTitle)
                .setSmallIcon(R.drawable.ic_alarm_black_24dp)
                .setSound(mUri)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .addAction(R.drawable.ic_icon_alarm, context.getString(R.string.pay_now), pendingIntent)
                .setCategory(NotificationCompat.CATEGORY_REMINDER)
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("Have you completed your task?"))
                .setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE)
                .setPriority(Notification.PRIORITY_HIGH);

        builder.setColor(ContextCompat.getColor(context, R.color.colorPrimary));
    }

    Notification notification = builder.build();
    mNotificationManager.notify(rowId, notification);
}

1 Ответ

0 голосов
/ 21 октября 2019

Добро пожаловать на вечеринку кодов ?

Как я видел, вы хотите начать действие, когда другой уже открыт, и он не может получить другие дополнения.

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

Отредактировано:

использовать это в своей деятельности

@Override
protected void onNewIntent(final Intent intent) {
    super.onNewIntent(intent);
    this.setIntent(intent); //just add this line when overrided
}

сделать это и обновить меня

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