Не удалось очистить уведомление и открыть фрагмент из уведомления - PullRequest
0 голосов
/ 08 января 2020

Я пытаюсь удалить уведомление. Но это остается там. Не удалось открыть фрагмент Activity из уведомления. Ниже мой код,

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int sticky;

        try {
            AndroidLogger.log(5, TAG, "Missed call notification on start");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
                NotificationChannel channel = new NotificationChannel("1", "Call Notification", importance);
                channel.setDescription("Get alert for missed call");
                channel.setShowBadge(true);
                channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                NotificationManager notificationManager = getSystemService(NotificationManager.class);
                notificationManager.createNotificationChannel(channel);
            }
            Intent notifyIntent = new Intent(this, ViewFragment.class);
            notifyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


            PendingIntent pIntent = PendingIntent.getActivity(this, 0, notifyIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
                    .setSmallIcon(R.drawable.nexge_logo)
                    .setContentTitle("Missed Call")
                    .setContentText(intent.getStringExtra("Number"))
                    .setContentIntent(pIntent)
                    .setAutoCancel(true)
                    .setPriority(Notification.PRIORITY_MAX);

            Notification buildNotification = mBuilder.build();
            NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            //mNotifyMgr.notify(1, buildNotification);

            startForeground(1,buildNotification);
        } catch (Exception exception) {
            AndroidLogger.error(1, TAG, "Exception while starting service", exception);
        }
        return START_NOT_STICKY;
    }
}

Кто-нибудь, помогите мне решить эту проблему. Заранее спасибо. Ниже мой другой вопрос, на который я не получил правильного ответа. Помогите мне с этим также Об уведомлении о пропущенном вызове в android

1 Ответ

0 голосов
/ 08 января 2020

Мое решение для аналогичной проблемы было изменение флага PendingIntent на PendingIntent.FLAG_ONE_SHOT Из документации Android:

Флаг, указывающий, что этот PendingIntent может использоваться только один раз. Для использования с getActivity (Context, int, Intent, int), getBroadcast (Context, int, Intent, int) и getService (Context, int, Intent, int).

Если установлено, после send () вызывается для него, он будет автоматически отменен для вас, и любая дальнейшая попытка отправки через него потерпит неудачу.

и добавление уведомления FLAG_AUTO_CANCEL flag:

mBuilder.flags |= Notification.FLAG_AUTO_CANCEL;

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

Редактировать : Сначала следует позвонить

Notification notification = mBuilder.build();

, затем

notification.flags = Notification.FLAG_AUTO_CANCEL;

Edit2 : только что заметил, что вы используете уведомление для startForeground(). Это означает, что уведомление будет оставаться в течение всего времени, пока ваша служба / действие работает (это по умолчанию, так что пользователь будет знать, что служба / деятельность все еще работает).

Уведомление будет оставаться как Пока ваш Сервис / Деятельность работает как основной сервис.

...