[英]Android - Remove action button from notification
单击这些操作按钮时,我想关闭通知操作按钮(而不是整个通知)。 (假设:带有停止操作按钮的下载通知。单击停止时,关闭停止按钮并将 contentText 更改为“下载已取消”)
我唯一想到的是取消通知并通知另一个具有相同 ID 的通知,但这似乎是一个丑陋的解决方法......
那么,有没有办法从通知中删除操作按钮?
(我认为没有必要放任何代码,但如果有必要我会......)
如果您使用的是 v4 支持库中的 NotificationCompat.Builder,您可以直接访问构建器的操作集合(遗憾的是没有提供公共修改器)。
以下将解决问题(当然您必须更新重新通知):
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
}
从这里: https : //code.google.com/p/android/issues/detail?id=68063
注意: Proguard 可能会破坏混淆构建中的按钮清除。 修复是在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());
Android 提供了通知区域,用于提醒用户已发生的事件。 它还提供了一个通知抽屉,用户可以下拉以查看有关通知的更多详细信息。
通知抽屉包括
要设置通知以便更新,请通过调用 NotificationManager.notify(ID, notification) 向其发出通知 ID。 要在发出通知后更新此通知,请更新或创建 NotificationCompat.Builder 对象,从中构建 Notification 对象,并使用您之前使用的相同 ID 发出通知。
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());
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.