Bruno Diego Bruno Diego - 1 year ago 133
Android Question

Android notification addAction not launching broadcast

Creating notification:

PendingIntent pIntent = PendingIntent.getActivity(context, (int) taskId, intent, 0);

PendingIntent pIntentMarkAsDone = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.addAction(0, context.getString(R.string.mark_as_done), pIntentMarkAsDone);

Notification notification =;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) taskId, notification);

I added the adding using a pending intent with getBroadcast.


public class NotificationReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// Log to check

This class should "receive" the action. I also add on Manifest


<receiver android:name=".NotificationReceiver">
<action android:name="<package_name>.MARK_AS_DONE"/>

Well, onReceive is not receiving. What am I doing wrong?

Answer Source

TL;DR: Create a fresh Intent, rather than reusing the one in intent, and get rid of the <intent-filter> from the <receiver>.

Your first line is:

PendingIntent pIntent = PendingIntent.getActivity(context, (int) taskId, intent, 0);

This implies that intent identifies some activity. If you created this via new Intent(context, YourActivityClass.class), then it has a ComponentName set inside of it, identifying your activity.

Then, you call setAction() on intent and use it with getBroadcast(). However, other than setting (or replacing) the action, everything else in intent is the same as it was. In particular, the ComponentName identifying the activity is still there. So, when the broadcast is sent, Android cannot deliver it, as the component is invalid (an activity cannot directly receive a broadcast), and the action string is ignored (as once a ComponentName is set on an Intent, things like actions and categories no longer count for routing).

So, I recommend that you create two Intent objects, one for the activity, one for the receiver.

Note that you do not need an action string for the receiver. You can use the explicit Intent constructor (new Intent(context, NotificationReceiver.class)). In fact, having the action string on the receiver is bad for security, as now any app can send you that broadcast. So, I recommend removing the <intent-filter> and using an explicit Intent to create your broadcast PendingIntent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download