2

開發音樂應用程序。在我的音樂服務中,我寫了一個自定義廣播接收器。它適用於Intent.ACTION_HEADSET_PLUG,但不適用於Intent.ACTION_MEDIA_BUTTONAndroid:如何從藍牙設備控制音樂服務播放/暫停?

請指導如何從藍牙設備控制音樂控制(播放/暫停/下一個/上一個)。

代碼Intent.ACTION_HEADSET_PLUG是:

@Override 
    public void onReceive(Context context, Intent intent) { 

     // aux 
     if(intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) 
     { 
      int state = intent.getIntExtra("state", -1); 

      if(state == 0) 
      { 
       // Headset is unplugged. PAUSE 
       pauseSong(); 
       sendBroadcast(); 
      } 
      else if(state == 1) 
      { 
       // headset is plugged 
       resumeSong(); 
       sendBroadcast(); 
      } 

     } 
    } 

回答

1

正如Media playback the right way talk解釋,你必須註冊爲「首選的媒體應用程序」。

ComponentName mediaButtonReceiver = 
    new ComponentName(context, YourBroadcastReceiver.class); 
MediaSessionCompat mediaSession = 
    new MediaSessionCompat(context, 
    tag, // Debugging tag, any string 
    mediaButtonReceiver, 
    null); 
mediaSession.setFlags(
    MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | 
    MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS); 
mediaSession.setCallback(this); // a MediaSessionCompat.Callback 

// This is what enables media buttons and should be called 
// Immediately after getting audio focus 
mediaSession.setActive(true); 
+0

我添加的代碼到我的項目,但它不工作:當您使用MediaSessionCompat作爲MediaSessionCompat video解釋這是容易得多。我觀看了視頻,看到在開始工作之前將更多東西添加到代碼中。 我們需要將元數據和setState設置爲mediaSession。但如何做到這一點沒有解釋。任何想法先生? – WideFide

+0

通過這個http://stackoverflow.com/questions/28547024/mediasession-does-not-show-background-on-lock-screen只是想通了:) – WideFide