java - 接收器从通知接收意图的问题
问题描述
我有一个将广播发送到广播接收器的代码。
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
将发送一个系统广播。反过来,这意味着您的接收器需要设置为接收系统广播,因为:
- 它在清单中使用
<receiver>
元素注册,或者 - 它是通过调用
registerReceiver()
aContext
(not onLocalBroadcastManager
)动态注册的
请注意,在 Android 8.0+ 上,隐式广播(仅具有操作字符串的广播)实际上是被禁止的。如果您选择在清单中注册您的接收器,请使用Intent
标识特定接收器的 (例如,new Intent(this, MyReceiverClass.class)
)。如果您选择通过registerReceiver()
...注册您的接收器,我认为有一个方法来处理它,但我忘记了细节。
推荐阅读
- python - 为什么 HERE API 中的 routingApi.matrix() 方法有时找不到两点之间的成本?
- php - 根据参考在关联 php 数组中添加键
- mysql - 使用更高的隔离级别会降低死锁的可能性吗?
- openedge - Progress4gl如何锁定自己?
- maven - 从 Netbeans 的 Maven 输出中删除 NETBEANS-ExecEvent 行
- coldfusion - 我应该在 onApplicationStart() 函数内部还是外部放置 DSN(数据源)定义?
- firefox - 无法在文本区域上下移动光标(Firefox 77.0.1(64 位)、Windows)
- html - 带溢出的弹性容器
- javascript - html 表单中的 JavaScript 验证
- python - Pandas groupby 结果 - 将一些分组的列值移动到新数据框的行中