我想在点击通知操作按钮时(而不是整个通知),关闭这些操作按钮。(比如:一个有“停止”操作按钮的下载通知。当点击“停止”后,关闭“停止”按钮,并将contentText更改为“下载已取消”)
我能想到的唯一方法就是取消通知并通过相同的id发布另一个通知,但这似乎是一个丑陋的解决方案......
那么,是否有任何方法可以从通知中删除操作按钮?
(我认为没有必要放置任何代码,但如果需要的话,我可以提供...)
我想在点击通知操作按钮时(而不是整个通知),关闭这些操作按钮。(比如:一个有“停止”操作按钮的下载通知。当点击“停止”后,关闭“停止”按钮,并将contentText更改为“下载已取消”)
我能想到的唯一方法就是取消通知并通过相同的id发布另一个通知,但这似乎是一个丑陋的解决方案......
那么,是否有任何方法可以从通知中删除操作按钮?
(我认为没有必要放置任何代码,但如果需要的话,我可以提供...)
如果你正在使用v4支持库中的NotificationCompat.Builder,你可以直接访问生成器的操作集合(不幸的是,没有提供公共mutators)。
以下操作可以解决问题(当然你必须更新re-notify):
NotificationCompat.Builder notifBuilder = NotificationCompat.Builder(context);
...
notifBuilder.mActions.clear();
我正在使用以下解决方法:
NotificationCompat.Builder builder = //existing instance of builder
//...
try {
//Use reflection clean up old actions
Field f = builder.getClass().getDeclaredField("mActions");
f.setAccessible(true);
f.set(builder, new ArrayList<NotificationCompat.Action>());
} catch (NoSuchFieldException e) {
// no field
} catch (IllegalAccessException e) {
// wrong types
}
proguard-rules.pro
中添加以下两行代码。-keep class androidx.core.app.NotificationCompat { *; }
-keep class androidx.core.app.NotificationCompat$* { *; }
我曾经遇到过同样的问题,并找到了解决方法。 我创建了另一个构建器,并添加了两个“空”操作,如下所示:
builder.addAction(0, null, null);
builder.addAction(0, null, null);
我有几个按钮,每个按钮都需要调用一次(如果你有三个按钮,就要调用三次)。
当调用 Notify 方法时,它会移除这些按钮。
尽管已接受的答案可行,但根据文档,执行此操作的设计方式是使用NotificationCompat.Extender
类。例如,在Kotlin中:
private val clearActionsNotificationExtender = NotificationCompat.Extender { builder ->
builder.mActions.clear()
builder
}
private val notificationBuilder by lazy {
NotificationCompat.Builder(context)
.addAction(R.drawable.ic_play_arrow, "Play", playPendingIntent)
}
private fun updateNotification(){
notificationBuilder
.extend(clearActionsNotificationExtender) // this will remove the play action
.addAction(R.drawable.ic_pause, "Pause", pausePendingIntent)
}
NotificationCompat.Builder notifBuilder = NotificationCompat.Builder(context);
移除整个操作按钮:
builder.mActions.clear();
移除特殊操作按钮:
builder.mActions.remove(index);
最后:
notificationManager.notify(notificationID, builder.build());
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You are downloading some image.")
.setSmallIcon(R.drawable.ic_stop)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText("Download canceled")
.setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is
// updated.
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
...
mActions
应该是一个私有成员,并且Google没有提供清除操作的方法。真是可惜... - MackovichRestrictedApi
) 显示,好像是一个错误,但它仍然可以工作。我不知道这样做的缺点。有没有人知道?从头开始创建NotificationBuilder
对象可能不是一个好的解决方案,因为在更新时它 "可能" 会导致通知弹出/闪烁。所以,我仍然使用它,而且盲目地忽略RestrictedApi
... - frankish