Home » Android » Android Notification Action not calling pending intent to service

Android Notification Action not calling pending intent to service

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am trying to get my on going notification to have a button, when clicked it should call my service which is controlling audio playback.

Here is my notification with the intent

        Intent intent = new Intent(context, AudioStreamService.class);


    Random generator = new Random();


    PendingIntent i = PendingIntent.getActivity(context, 579, intent,PendingIntent.FLAG_UPDATE_CURRENT);


    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(text)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setLargeIcon(picture)
            .setTicker(ticker)
            .setNumber(number)
            .setOngoing(true)
            .addAction(
               R.drawable.ic_action_stat_reply,
               res.getString(R.string.action_reply),
               i);

    notify(context, builder.build());

Here is the on start for my service

    public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("APP ID", "APP ID - service called ");

    if(isPlaying){
        stop();
    }
    else {
        play();
    }
    return Service.START_STICKY;
}

The log is never triggered when called from the action in the notification. But the service is used by a button in the app and works fine. Log gets called as do commands below.

How to&Answers:

Use :

PendingIntent pendingIntent = PendingIntent.getService(context, 579, intent,PendingIntent.FLAG_UPDATE_CURRENT);

instead of :

PendingIntent pendingIntent = PendingIntent.getActivity(context, 579, intent,PendingIntent.FLAG_UPDATE_CURRENT);

^^ This is used to start an activity from the notification.