我有一個將廣播發送到廣播接收器的代碼。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"));主要目的是達到以下結果:當用戶單擊通知中的上一個按鈕時,將播放上一首歌曲。但是當我運行應用程序并選擇音樂時,我不能像以前一樣聽音樂。因此,似乎某處存在永久循環。怎么了?如果我只想播放一首之前的歌曲而不是之前的所有歌曲,如何解決這個問題?
1 回答

Cats萌萌
TA貢獻1805條經驗 獲得超9個贊
廣播有兩種類型:系統廣播和本地廣播。
本地廣播通過LocalBroadcastManager
獨家工作。如果您看到與“廣播”相關的任何其他內容,99.99% 的時間,那是指系統廣播。
特別是,PendingIntent.getBroadcast()
給你一個PendingIntent
將發送一個系統廣播。反過來,這意味著您的接收器需要設置為接收系統廣播,因為:
它在清單中使用
<receiver>
元素注冊,或者它是通過調用
registerReceiver()
aContext
(not onLocalBroadcastManager
)動態注冊的
請注意,在 Android 8.0+ 上,隱式廣播(僅具有操作字符串的廣播)實際上是被禁止的。如果您選擇在清單中注冊您的接收器,請使用Intent
標識特定接收器的 (例如,new Intent(this, MyReceiverClass.class)
)。如果您選擇通過registerReceiver()
...注冊您的接收器,我認為有一個方法來處理它,但我忘記了細節。
添加回答
舉報
0/150
提交
取消