2010-11-03 85 views
10

我試圖暫停拔下耳機時正在播放的音樂。活動開始時收到Intent.ACTION_HEADSET_PLUG

我已經創建了一個偵聽ACTION_HEADSET_PLUG意圖和對他們的行爲時,狀態額外爲0(對於不插電)一個BroadcastReceiver。我的問題是,無論活動何時開始,我的BroadcastReceiver都會收到ACTION_HEADSET_PLUG意圖。這不是我期望的行爲。我期望只有在插入或拔下耳機時才能解除意圖。

是不是有一個原因,ACTION_HEADSET_PLUG意圖被注入一個接收器與該IntentFilter後立即被捕獲?有沒有一種明確的方式可以解決這個問題?

我會假設既然默認的音樂播放器實現了類似的功能,當耳機被拔出,這是可能的。

我錯過了什麼?

這是註冊碼

registerReceiver(new HeadsetConnectionReceiver(), 
       new IntentFilter(Intent.ACTION_HEADSET_PLUG)); 

這是HeadsetConnectionReceiver

public class HeadsetConnectionReceiver extends BroadcastReceiver { 

    public void onReceive(Context context, Intent intent) { 
     Log.w(TAG, "ACTION_HEADSET_PLUG Intent received"); 
    } 

} 

回答

15

感謝您的回覆傑克。我應該更新原文,以表明我發現了我遇到的問題。經過一番研究後,我發現ACTION_HEADSET_PLUG Intent在Context中使用sendStickyBroadcast方法進行廣播。

Sticky Intents在廣播後由系統保存。無論何時註冊新的BroadcastReceiver以接收該Intent。它在包含最後更新值的註冊後立即觸發。對於頭戴式耳機,這對於在首次註冊接收器時能夠確定頭戴式耳機已插入很有用。

這是我用於接收ACTION_HEADSET_PLUG意圖的代碼:

private boolean headsetConnected = false; 

public void onReceive(Context context, Intent intent) { 
    if (intent.hasExtra("state")){ 
     if (headsetConnected && intent.getIntExtra("state", 0) == 0){ 
      headsetConnected = false; 
      if (isPlaying()){ 
       stopStreaming(); 
      } 
     } else if (!headsetConnected && intent.getIntExtra("state", 0) == 1){ 
      headsetConnected = true; 
     } 
    } 
} 
+0

另一種解決方案是使用removeStickyBroadcast()方法,用於在服務正在處理時不能忽略命令的情況。 – greg7gkb 2011-04-22 02:17:54

+16

我認爲更好的解決方案是在接收器中使用[isInitialStickyBroadcast()](http://developer.android.com/reference/android/content/BroadcastReceiver.html#isInitialStickyBroadcast%28%29)。這不需要定義刪除粘性廣播的權限,也不會對其他應用程序造成副作用。 – amram99 2011-08-17 14:41:04

+0

再次道格。我可能誤解了這個意圖,android的接收器系統。但是,你如何獲得isPlaying,我會認識到他們在你原來的活動? :-) – 2011-10-27 14:21:54

-2

的我遇到了同樣的問題定義。我不確定是什麼原因造成的,但至少在我的測試中它似乎是一致的,這意味着你可以解決它。我通過添加一個布爾成員變量來啓動true,並在第一個onReceive(Context, Intent)調用中設置爲false。然後該標誌控制我是否實際處理拔下事件。

僅供參考,以下是我使用的代碼,可在here的環境中使用。

private boolean isFirst; 

public void onReceive(Context context, Intent intent) 
{ 
    if(!isFirst) 
    { 
     // Do stuff... 
    } 
    else 
    { 
     Log.d("Hearing Saver", "First run receieved."); 
     isFirst = false; 
    } 
} 
+1

更好地利用isInitialStickyBroadcast()。 – 2016-01-03 20:14:56

0

我用不同的方法來停止播放時耳機拔出。我不希望你使用它,因爲你已經很好,但其他一些人可能會覺得它很有用。如果你的聲音聚焦控制,那麼Android將會給你一個事件音頻變得嘈雜,所以如果你寫一個接收器爲這個事件它看起來就像在另一個評論建議

public void onReceive(Context context, Intent intent) { 
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) { 
     if (isPlaying()){ 
      stopStreaming(); 
     } 
    } 
}