Подтвердить что ты не робот

Удаление уведомления после нажатия

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

Я попытался работать со следующим кодом:

import android.app.NotificationManager;

public class ExpandNotification {
     private int NOTIFICATION = 546;
     private NotificationManager mNM;

     public void onCreate() {
        mNM.cancel(NOTIFICATION);
        setContentView(R.layout.activity_on);
        //Toast.makeText(this, "stopped service", Toast.LENGTH_SHORT).show();
    }

Я думаю, что этот код выполняет другой класс при нажатии?

PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, new Intent(this, ExpandNotification.class), 0);

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

4b9b3361

Ответ 1

Используйте флаг Notification.FLAG_AUTO_CANCEL

Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent);

// Cancel the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;

и запустить приложение:

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

// Create a new intent which will be fired if you click on the notification
Intent intent = new Intent(context, App.class);

// Attach the intent to a pending intent
PendingIntent pendingIntent = PendingIntent.getActivity(context, intent_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Ответ 2

Если это кому-то помогает: Чтобы получить тот же эффект, используя Notification.Builder или NotificationCompat.Builder вызов setAutoCancel(true) в экземпляре Builder.

Ответ 3

Этот ответ слишком поздний, но особенно я пишу следующее решение, потому что конструктор уведомлений устарел, поэтому используйте уведомление с помощью построителя, например:

 **.setAutoCancel(true)** is used to remove notification on click

и полное уведомление похоже на следующее:

  private void makeNotification(String title,String msg){

    Intent resultIntent = new Intent(this, MasterActivity.class);

    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    this,
                    0,
                    resultIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setContentIntent(resultPendingIntent)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(title)
                    .setAutoCancel(true)
                    .setContentText(msg);

    int mNotificationId = 001;
    NotificationManager mNotifyMgr =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mNotifyMgr.notify(mNotificationId, mBuilder.build());

}

Вызов этого метода с заголовком и сообщением вы получите отличное уведомление.

Ответ 4

Лучший и простой способ: установить builder.setAutoCancel(true), чтобы отменить уведомление после нажатия на уведомление. Надеюсь, этот код поможет вам.

Builder для уведомления

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.btn_star);
builder.setContentTitle("This is title of notification");
builder.setContentText("This is a notification Text");
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

Для открытия активности при нажатии уведомления

Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);

Показать имя в уведомлении

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(114, builder.build());

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

public void ShowIntentNotification(View v)
    {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(android.R.drawable.btn_star);
        builder.setContentTitle("This is title of notification");
        builder.setContentText("This is a notification Text");
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

        Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(pendingIntent);
        builder.setAutoCancel(true);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(114, builder.build());

    }