Remote view in android : Auto Cancel Custom Notification

Total Post:17

 1925  View(s)
Rate this:
I am using remote view to create a custom layout  notification , i want to auto cancel the notification once the user touches it 

RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.notification_layout);      
    NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, RQST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    remoteView.setOnClickPendingIntent(, pIntent);
    Notification notify =;
    notify.flags |= Notification.FLAG_AUTO_CANCEL;
    NotificationManager notiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notiManager.notify(NOTY_ID, notify);
  1. Post:397

    Re: Remote view in android : Auto Cancel Custom Notification

    The way I achieved this is by creating BroadcastReceiver which controls button clicks from Notification. Create something like this :

    public class NotificationButtonListener extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            int action = intent.getIntExtra("mode", -1);
            switch (action) {
                // do some things depending on action if there are more stuff to do
    Don't forget to add your BroadcastListener to your manifest file:

    <receiver android:name=".NotificationButtonListener">
    And you can create a helper class for creating and cancelling notification:

    public class NotificationHelper {
        private static final int NOTIFICATION_ID = 5;
        private static NotificationManager mNotificationManager = null;
        public static void showNotification(Context context) {
            mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
            contentView.setOnClickPendingIntent(, closePendingIntent);
            Intent mMainIntent = new Intent(context, MainActivity.class);
            mMainIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent mMainPendingIntent = PendingIntent.getActivity(context, 555, mMainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            Notification notification =;
            mNotificationManager.notify(NOTIFICATION_ID, notification);
        public static void cancelNotification() {
            if (mNotificationManager != null) {

    And using that class in your NotificationButtonListener you can call NotificationHelper.cancelNotification();



Enter your email address here always to be updated. We promise not to spam!