Search code examples
javaandroidkotlinandroid-notificationsandroid-notification-action

How to perform a custom task from a action button click in notification?


I have a notification in my app and I want to perform a custom task on clicking of the action in the notification. I have done this to add a action:

timerNotificationBuilder.addAction(0, "STOP", null /*What to add here ?*/ );

But, I want to stop a handler from running on click of this action. I have only seen to open activities using this. But, how to stop a handler or any custom task?

Thanks 😀


Solution

  • @Sambhav.K , You need to pass Pending Intent in action button like below code

      notificationBuilder.addAction(mCallAction)
    
      val mCallAction = NotificationCompat.Action.Builder(
                R.drawable.ic_reject_call,
                "Stop",
                mPendingIntent
            )
    
    
         val mCallIntent = Intent(context,   CustomActionReceiver::class.java)
       
        val mPendingIntent = PendingIntent.getBroadcast(
            context, 999,
            mCallIntent, PendingIntent.FLAG_UPDATE_CURRENT
        )
    

    and create new CustomActionReceiver class and do your stuff what you want like below

    class CustomActionReceiver : BroadcastReceiver() {
    
    override fun onReceive(context: Context, intent: Intent) {
       // Do your Stuff
    }}