簡體   English   中英

從通知接收Intent的Receiver問題

[英]Problem with Receiver which receives Intents from Notification

我有一個代碼,用於向廣播接收器發送廣播。

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

主要目的是達到以下結果:當用戶點擊通知中的按鈕Previous時,將播放上一首歌曲。 但是,當我運行應用程序並選擇音樂時,我無法聽音樂,就像以前的播放一樣。 所以,似乎某處有一個永久的循環。 怎么了? 如果我只想播放以前的一首歌而不是之前的所有歌曲,如何解決這個問題?

有兩種類型的廣播:系統廣播和本地廣播。

本地廣播通過LocalBroadcastManager工作。 如果您看到與“廣播”相關的任何其他內容,99.99%的時間是指系統廣播。

特別是, PendingIntent.getBroadcast()為您提供了一個發送系統廣播的PendingIntent 反過來,這意味着您的接收器需要設置為接收系統廣播,因為:

  • 它在清單中注冊了<receiver>元素,或
  • 通過在Context (而不是在LocalBroadcastManager )調用registerReceiver()來動態registerReceiver()

請注意,在Android 8.0+上,隱式廣播(僅包含操作字符串的廣告)實際上是被禁止的。 如果您選擇在清單中注冊接收方,請使用標識特定接收方的Intent (例如, new Intent(this, MyReceiverClass.class) )。 如果您選擇通過registerReceiver()注冊您的接收器...我認為有一個如何處理它的方法,但我忘記了細節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM