Problem with Receiver which receives Intents from Notification

Sergei Mikhailovskii :

I have a code that send a broadcast to a broadcast receiver.

Intent intentPrev = new Intent(ACTION_PREV);
        PendingIntent pendingIntentPrev = PendingIntent.getBroadcast(this, 0, intentPrev, PendingIntent.FLAG_UPDATE_CURRENT);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intentPrev);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, notification);

In another class I have a Receiver:

private BroadcastReceiver NotificationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("PREVIOUS")){
                playPrev();
            }
        }
    };

And in onCreate method I register this receiver:

LocalBroadcastManager.getInstance(this).registerReceiver(NotificationReceiver, new IntentFilter("PREVIOUS"));

The main aim was to reach the following result: when user clicks on button Previous in notification, the previous song will play. But when I run the app and choose the music I can't listen to music, as always the previous plays. So, it seems that there's a perpetual loop somewhere. What's the matter? How to solve this problem if I want to play only one previous song but not all previous songs?

CommonsWare :

There are two types of broadcasts: system broadcasts and local broadcasts.

Local broadcasts work through LocalBroadcastManager exclusively. If you see anything else tied to "broadcast", 99.99% of the time, that is referring to system broadcasts.

In particular, PendingIntent.getBroadcast() gives you a PendingIntent that will send a system broadcast. That, in turn, means that your receiver needs to be set up to receive a system broadcast, either because:

  • It is registered in the manifest with a <receiver> element, or
  • It is registered dynamically by calling registerReceiver() on a Context (not on LocalBroadcastManager)

Note that on Android 8.0+, implicit broadcasts (ones with just an action string) are banned, in effect. If you elect to register your receiver in the manifest, use an Intent that identifies the specific receiver (e.g., new Intent(this, MyReceiverClass.class)). If you elect to register your receiver via registerReceiver()... I think there is a recipe for how to handle that, but I forget the details.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=106756&siteId=1