Android Notification Action is not fired (PendingIntent)

MrHill picture MrHill · Feb 12, 2013 · Viewed 16.2k times · Source

I am trying to add an Notification action item in my app which is a music player. When a stream is started a notification should be triggered and an stop button for the stream should be displayed in the notfication. The notification working fine so far, I am having trouble with the stop action item. Here is how it is declared in the service starting the stream:

Intent stopIntent = new Intent(this, MusicPlayerNew.class);
stopIntent.putExtra("STOP", "STOP");
PendingIntent stopPendingIntent = PendingIntent.getActivity(this, 0,
                stopIntent, PendingIntent.FLAG_UPDATE_CURRENT, null);
mBuilder.addAction(R.drawable.ic_stat_stop, "Stop", stopPendingIntent);

Now in the onResume()-method of my activity I check with getIntent().getStringExtra() for the "STOP" extra, but the intent I retrieved via getIntent() has no extras set :(

I also tried to check to send an broadcast (i have a broadcast receiver working to communicate from the service to the activity)

Intent stopIntent2 = new Intent(MusicPlayerNew.STOP_MEDIAPLAYER);
PendingIntent stopPendingIntent2 = PendingIntent.getBroadcast(this, 0,
                stopIntent2, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.ic_stat_stop, "Stop", stopPendingIntent2); 

Now this works if the activity is currently in the foreground. If the activity is in the background the stop button does nothing :(

EDIT: I have the BroadcastReceiver in my Activity as a private class

private class DataUpdateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
..
}}

In the onResume() register my app for this receiver:

intentFilter = new IntentFilter(STOP_MEDIAPLAYER);
registerReceiver(dataUpdateReceiver, intentFilter);

onPause()

unregisterReceiver(dataUpdateReceiver);

Now if I remove the unregistering from the onPause()-method the broadcast is received even if the app/activity is not in the foreground anymore. But is this the right way to do it? I got this register/unregister-stuff from a tutorial on the web i think..

Answer

Ayman Al-Absi picture Ayman Al-Absi · Jun 17, 2016

This is very late answer but it may help someone:

You should choose the right kind of Pending intent based on the intent you want to run. Here are some Examples:

For Activity use below:

Intent i = new Intent(this, YourActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);

For Service use below:

Intent i = new Intent(this, YourService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);

For Broadcast Receiver use below:

Intent i = new Intent(this, YourReciver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

You may need to change the request code and Flags if required