【问题标题】:Trigger function on notification action click通知动作点击触发功能
【发布时间】:2025-12-13 02:00:02
【问题描述】:

我正在用 Kotlin 编写一个应用程序,它应该显示一个带有操作按钮的通知。

我有课。我们就叫它NotificationClass

本课程通过fun createNotification()为我创建通知

这一切都很好。但是我想在通知中添加一个按钮,单击该按钮会触发我的NotificationClass 中称为notificationActionClicked() 的函数。

有什么办法可以做到吗?

(通知类不是android服务。它只是一个实用程序类。)

【问题讨论】:

标签: android notifications kotlin android-notifications notification-action


【解决方案1】:

您需要查看待处理的意图

 public void createNotification(View view) {
    // Prepare intent which is triggered if the
    // notification is selected
    Intent intent = new Intent(this, NotificationReceive.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);

    // Build notification
    Notification noti = new Notification.Builder(this)
            .setContentTitle("New mail from " + "test@gmail.com")
            .setContentText("Subject").setSmallIcon(R.drawable.icon)
            .setContentIntent(pIntent)
            .addAction(R.drawable.icon, "Call", pIntent)
            .addAction(R.drawable.icon, "More", pIntent)
            .addAction(R.drawable.icon, "And more", pIntent).build();
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // hide the notification after its selected
    noti.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, noti);

}

【讨论】: