我有一个发送广播的广播接收器代码。
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()
在Context
动态注册(不LocalBroadcastManager
)请注意,在Android 8.0+,隐广播(的人只有一个动作字符串)都被禁止,有效。如果您选择注册在清单接收器,可使用标识特定的接收器(例如,Intent
)的new Intent(this, MyReceiverClass.class)
。如果您选择通过registerReceiver()
注册您的接收器...我认为这是对如何处理配方,但我忘了细节。