安卓:通知操作以关闭通知

5
我正在尝试创建一个带有操作按钮的Android通知。我已经设置了一个可以启动活动的通知,但我想要另一个通知可以关闭通知而不需要将用户带到其他屏幕/活动(不会进入我的应用程序的任何部分)。
我不想使用“ .auto cancel(true)”,因为我希望除非按下此操作按钮,否则通知将保留。
主要用途是针对持续通知,因为它们无法通过滑动删除。这个想法类似于带有“解除”操作的Android日历。

你能详细说明一下吗?你的目标API级别是什么?使用Jellybean+通知,你应该能够完成所有这些操作。 - cbrulak
我正在使用jellybean api - 我已经创建了一个启动活动的操作,但我无法弄清楚如何不启动活动。我可以使用广播接收器,但我不知道是否能够清除通知。基本上,我希望通知操作可以清除自己(通知)。 - user2442638
2个回答

2
当通知被创建时,将通知发送至广播接收器。当通知操作被按下时,广播接收器会启动,因此广播接收器中的cancel()方法会取消该通知。

9
你能提供这个的确切代码吗?我无法按照你的说明进行操作。谢谢。 - ARK

2

在我看来,使用broadcastReceiver是一种更清晰的方式来取消通知:

在AndroidManifest.xml中:

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

在Java中的文件。
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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接