我正在尝试为我的应用程序创建通知,其具有当我单击它时可以更改其图标、标题和意图的操作。我在这里看到可能是在3:33 https://www.youtube.com/watch?v=tKoQatxG0_8&index=73&list=PLOU2XLYxmsIIwGK7v7jg3gQvIAWJzdat_ 可以实现,但我找不到一种方法来实现它。另外,如果有人知道如何在链接中的Right watch上使用暂停/播放图标,则也希望了解。提前致谢。
Notification status = null;
private NotificationCompat.Builder mBuilder;
private NotificationManager mManager;
private final int STATUS_ID = 1;
private String CHANNEL_ID = "channel_name";
private void setUpNotification() {
mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int playOrPause;
if(isPlaying()) {
playOrPause = R.drawable.ic_pause;
} else {
playOrPause = R.drawable.ic_play;
}
if(mBuilder == null) {
//Setup Builder
mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
mBuilder.setOngoing(true)
.addAction(playOrPause, "play", pendingIntent1) // Index 0
.addAction(R.drawable.ic_2, "text2", pendingIntent2) // Index 1
.addAction(R.drawable.ic_3, "text3", pendingIntent3);// Index 2
status = mBuilder.build();
} else {
//Update builder as per your needs
mBuilder.setContentTitle(title);
status = mBuilder.build();
status.actions[0] = new Notification.Action(playOrPause, "play", pendingIntent1);
}
startForeground(STATUS_ID, status);
}
通过遵循 @Sammer J 的建议,我想出了以下解决方案。
try {
// mBuilder is a Notification.Builder object.
Field field = mBuilder.getClass().getDeclaredField("mActions");
field.setAccessible(true);
ArrayList<Notification.Action> mActions = (ArrayList<Notification.Action>) field.get(mBuilder);
if (mActions != null) {
mActions.set(0, new Notification.Action(R.drawable.ic_action_resume, getString(R.string.button_resume), pendingIntent));
field.set(mBuilder, mActions);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
mNotificationManager.notify(ONGOING_NOTIFICATION_ID, mBuilder.build());