我有一个向广播接收器发送广播的代码。
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"));
主要目的是达到以下结果:当用户点击通知中的上一首按钮时,将播放上一首歌曲。但是当我运行应用程序并选择音乐时,我无法像以前一样听音乐。所以,似乎某处有一个永久循环。怎么了?如果我只想播放之前的一首歌曲而不是之前的所有歌曲,如何解决这个问题?
最佳答案
广播有两种类型:系统广播和本地广播。
本地广播通过 LocalBroadcastManager
工作独家。如果您看到任何其他与“广播”相关的内容,99.99% 的情况下,这是指系统广播。
特别是,PendingIntent.getBroadcast()
给你一个 PendingIntent
这将发送一个系统广播。反过来,这意味着您的接收器需要设置为接收系统广播,原因可能是:
- 它在 list 中注册为
<receiver>
元素,或 - 通过调用
registerReceiver()
动态注册在Context
上(不在LocalBroadcastManager
上)
请注意,在 Android 8.0+ 上,隐式广播(仅带有操作字符串的广播)实际上是被禁止的。如果您选择在 list 中注册接收器,请使用 Intent
标识特定接收者(例如 new Intent(this, MyReceiverClass.class)
)。如果您选择通过 registerReceiver()
注册您的接收器...我认为有一个解决方法,但我忘记了细节。
关于java - 从通知接收 Intent 的 Receiver 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54504405/