简体   繁体   中英

Android: Notification action to dismiss the notification

I'm trying to create an android notification with action buttons. I have already set one up which starts an activity, but I would like another which dismisses the notification and doesn't take the user to another screen/Activity (not taken to any part of my app)

I don't want to use '.auto cancel(true) ' because I want the notification to be kept unless this action button is pressed.

The primary use would be for ongoing notifications as they cannot be removed with a swipe. The idea is similar to the android calender with the 'dismiss' action.

When the notification is created, send the notification to a broadcastreceiver. The broadcast receiver is them started when the notification action is pressed, so the cancel() in the broadcast receiver cancels the notification.

IMO Using a broadcastReceiver is a cleaner way to cancel a Notification:

In AndroidManifest.xml:

<receiver
     android:name=.NotificationCancelReceiver" >
     <intent-filter android:priority="999" >
         <action android:name="com.example.cancel" />
     </intent-filter>
</receiver>

In java File

Intent cancel = new Intent("com.example.cancel");
PendingIntent cancelP = PendingIntent.getBroadcast(context, 0, cancel, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Action actions[] = new NotificationCompat.Action[1];

NotificationCancelReceiver:

public class NotificationCancelReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         //Cancel your ongoing Notification
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM