2013-02-05 151 views
5

我需要檢測插入有線耳機是否有麥克風。檢測耳機是否有麥克風

我可以檢查是否使用isWiredHeadSetOn()插入耳機,但麥克風在AudioManager類中似乎不是這種方法。

我發現了一些使用ACTION_HEADSET_PLUG的建議,但即使在打開我的應用程序之前插入了耳機,我也有興趣瞭解此信息,但在我的應用程序生命週期中,此事件不會被解僱。

關於這個問題的任何想法?先謝謝你。

+0

你爲什麼需要它?這是由用戶知道麥克風的位置 – njzk2

+0

因爲我想通過音頻插孔連接閃光燈,這有助於我區分兩種類型的閃光燈。 – niculare

+1

音頻插座中有閃光燈嗎?我們能做到這一點 ? – njzk2

回答

12

UPDATE: 繼續前進,在活動的onResume()註冊ACTION_HEADSET_PLUG。 如果用戶在啓動後插入/拔出耳機,平臺將在恢復時向您的活動提供最新狀態。

下面的測試代碼工作:

package com.example.headsetplugtest; 

import android.app.Activity; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.util.Log; 

public class HeadSetPlugIntentActivity extends Activity { 

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      final String action = intent.getAction(); 
      if (Intent.ACTION_HEADSET_PLUG.equals(action)) { 
       Log.d("HeadSetPlugInTest", "state: " + intent.getIntExtra("state", -1)); 
       Log.d("HeadSetPlugInTest", "microphone: " + intent.getIntExtra("microphone", -1)); 
      } 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 

     IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); 
     getApplicationContext().registerReceiver(mReceiver, filter); 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 

     getApplicationContext().unregisterReceiver(mReceiver); 
    } 
} 
+0

謝謝!我不知道在活動開始時也調用onReceive() – niculare

+1

是不是FLAG_RECEIVER_REGISTERED_ONLY種類的設備連接廣播?即「在發送廣播時,只有已註冊的接收者纔會被呼叫 - 沒有BroadcastReceiver組件將被啓動」 - 或者如Dianne Hackborn所描述的那樣:「只給那些調用registerReceiver而不發送給在清單中聲明的​​接收者的人。 – Michael

+0

@邁克爾,你是對的。上面更新了我的答案。 – ozbek