How To Dismiss Notification Without Intent?

I want to display a notification inside the app that disappears when the notification is tapped without starting an activity.

I use an empty intent and it works:

Intent intent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(context, (int)System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "")

However, there are some crashes:

java.lang.RuntimeException: bad array lengths
    at android.os.Parcel.readIntArray(

According to this SO answer the crashes seem to happen because intent is not starting an activity.

A notification can be dismissed by its ID, but I cannot dismiss it when there is no activity to start and call the dismiss method.

How can I dismiss the notification on tap inside the app without using an empty intent?


According to this SO questions it seems to be an Android issue. The crashes I got reported also happened on Android 4.3.

Update 2:

According to this SO answer it seems to be due to a too large bitmap set with setLargeIcon. So I am reducing the bitmap size now with Glide.



You can create an intent which calls a BroadcastReceiver which then cancels the notification.

Your PendingIntentcan be created like this:

private PendingIntent getCancelNotificationIntent() {
    Intent cancelIntent = new Intent(context, CancelNotification.class);
    return PendingIntent.getBroadcast(context, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);

The class would look similar to this:

public class CancelNotification extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {

NOTIFICATION_ID is a constant you define and pass to the NotificationManager like this:

notificationManager.notify(NOTIFICATION_ID, yourNotificationObject);

NOTE: don't forget to register the receiver in your manifest file like this:

<receiver android:name="com.example.package.CancelNotification" />