Removing notification after click

后端 未结 6 1443
臣服心动
臣服心动 2020-12-15 15:44

I just started working with notifications and now I\'m trying to remove the notification and launch the app once the notification has been tapped in the notificationcenter.<

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 16:31

    Best & simple way is set builder.setAutoCancel(true) it's cancel your notification after clicking on notification. I hope this code help you.

    Builder for notification

    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));
    

    For open an activity on clicking notification

    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);
    

    Show bulder in notification

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

    Complete code for show a notification with icon, image, title, description, auto cancel and on click open an activity

    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());
    
        }
    

提交回复
热议问题