Trigger function on notification action click

1.9k views Asked by At

I am writing an app in Kotlin that should display a notification with an action button.

I have a class. Let's call it NotificationClass

This class creates notifications for me via fun createNotification()

This all works fine. But I want to add a button to the notification that, when clicked, triggers a function in my NotificationClass called notificationActionClicked().

Is there a way I can do this?

(The notification class is not an android service. It's just an utility class.)

1

There are 1 answers

0
umesh vashisth On

you need to take look about pending intent

 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 " + "[email protected]")
            .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);

}