首页 > 解决方案 > 接收器从通知接收意图的问题

问题描述

我有一个将广播发送到广播接收器的代码。

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);

在另一堂课上,我有一个Receiver

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

onCreate方法中我注册了这个接收器:

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

主要目的是达到以下结果:当用户单击通知中的上一个按钮时,将播放上一首歌曲。但是当我运行应用程序并选择音乐时,我不能像以前一样听音乐。因此,似乎某处存在永久循环。怎么了?如果我只想播放一首之前的歌曲而不是之前的所有歌曲,如何解决这个问题?

标签: javaandroidandroid-broadcast

解决方案


广播有两种类型:系统广播和本地广播。

本地广播通过LocalBroadcastManager 独家工作。如果您看到与“广播”相关的任何其他内容,99.99% 的时间,那是指系统广播。

特别是,PendingIntent.getBroadcast()给你一个PendingIntent将发送一个系统广播。反过来,这意味着您的接收器需要设置为接收系统广播,因为:

  • 它在清单中使用<receiver>元素注册,或者
  • 它是通过调用registerReceiver()a Context(not on LocalBroadcastManager)动态注册的

请注意,在 Android 8.0+ 上,隐式广播(仅具有操作字符串的广播)实际上是被禁止的。如果您选择在清单中注册您的接收器,请使用Intent标识特定接收器的 (例如,new Intent(this, MyReceiverClass.class))。如果您选择通过registerReceiver()...注册您的接收器,我认为有一个方法来处理它,但我忘记了细节。


推荐阅读