Android: Notification动作,取消通知



我正在尝试创建一个带有操作按钮的android通知。我已经设置了一个启动一个活动,但我想另一个解散通知,不带用户到另一个屏幕/活动(不采取我的应用程序的任何部分)

我不想用'。自动取消(真正的)’因为我想让通知保持,除非这个动作按钮被按下。

主要用于正在进行的通知,因为它们不能通过滑动删除。这个想法类似于android日历的"解散"动作。

创建通知后,将通知发送给broadcastreceiver。广播接收器在按下通知动作时启动,因此广播接收器中的cancel()将取消通知。

IMO使用broadcastReceiver是一种更简洁的取消通知的方式:

在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
    }
}

最新更新