Search code examples
androidandroid-intentnotificationsandroid-serviceandroid-pendingintent

Make addAction work for android notification


I'm trying to do something when user hits action button in the notification. Notifications are showing with action button present. Yet for some reason, action is not firing; receiver is not getting the message. In fact, neither receiver is getting the intent - WakefulBroadcastReceiver (for alerts), BootReceiver (to set up alert upon boot).

The code is below:

public class OSService extends IntentService {

        // Call this method from onHandleIntent
        private void createNotification(OrderSearch search)
            {
                String name = search.getName();
                NumberFormat df = NumberFormat.getIntegerInstance();
                Context context = getApplicationContext();

                Intent intent = new Intent("snooze");
                PendingIntent snoozer = PendingIntent.getBroadcast(context, 12345, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_stat_notify)
                        .setContentTitle(df.format(search.getOrderCount()) + " orders")
                        .setAutoCancel(true)
                        .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notify2))
                        .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
                        .addAction(R.drawable.ic_alarm_off_black_18dp, "for today", snoozer)
                        .setContentText(name);


                NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                manager.notify(1, builder.build());
            }
}

In manifest file:

<application ...>
   <receiver a:name=".ActionReceiver"/>
</application>

The action receiver:

public class ActionReceiver extends BroadcastReceiver
    {
        public void onReceive(Context context, Intent intent)
            {
                Log.i(getClass().getSimpleName(), "Action: " + intent.getAction());
            }
    }

I've been banging my head on the wall for a few days and can't see what's wrong.


Solution

  • Your Intent is for an action of "snooze". Your <receiver> does not have an <intent-filter>, let alone one for "snooze". If you are intending to invoke ActionReceiver for the Notification action, replace:

    Intent intent = new Intent("snooze");
    

    with:

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