[置顶] Android代码-----检测手机耳机插拔

时间:2022-02-24 19:05:02

AudioManager就有这个方法:isWiredHeadsetOn()

如果插入了耳机,就返回true,否则false;

当然,要加个权限,不然一直是返回false。

 <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

开始我追了好久的源码。发现了实时检测耳机插入和拔出的过程,不过对我的需求来说帮助不是很大。

实时检测耳机插入和拔出:

每当插入和拔出耳机时,系统都会发送Intent广播, 所以,只需要用一个receiver把这个广播intent(获取的action是:“android.intent.action.HEADSET_PLUG”)截获就好。

这个receiver必须要用代码注册,而不能写在manifest里面用写入内存的方式。

在Android下实现检测耳机插入和拔出,也即建立一个Broadcast Receiver,监听“android.intent.action.HEADSET_PLUG”广播

但直接在AndroidManifest.xml中添加一个<receiver>标签是无效的,如:

<receiver android:name=".HeadsetPlugReceiver">  
<intent-filter>  
  <action android:name="android.intent.action.HEADSET_PLUG" android:enabled="true"></action>  
</intent-filter>  
</receiver>

你会发现Receiver的onReceive事件永远不会被触发,解决方法就是手动编写代码注册该广播。

首先,创建一个BroadcastReceiver的子类,用于监听耳机插入和拔出:

public class HeadsetPlugReceiver extends BroadcastReceiver {  

    private static final String TAG = "HeadsetPlugReceiver";  

    @Override  
    public void onReceive(Context context, Intent intent) {  
      if (intent.hasExtra("state")){  
        if (intent.getIntExtra("state", 0) == 0){
          Toast.makeText(context, "headset not connected", Toast.LENGTH_LONG).show();  
        }  
        else if (intent.getIntExtra("state", 0) == 1){  
          Toast.makeText(context, "headset connected", Toast.LENGTH_LONG).show();  
        }  
      }  
    }  

}  

然后,在需要监听该事件的Activity中的onCreate()中注册监听该广播,同时不要忘记在onDestroy()中注销监听该广播:

public class TestHeadSetPlugActivity extends Activity {  

  private HeadsetPlugReceiver headsetPlugReceiver;  
  /** Called when the activity is first created. */  
  @Override  
  public void onCreate(Bundle savedInstanceState) {  
      super.onCreate(savedInstanceState);  
      setContentView(R.layout.main);  

      /* register receiver */  
      registerHeadsetPlugReceiver();  
  }  

  private void registerHeadsetPlugReceiver() {  
    headsetPlugReceiver = new HeadsetPlugReceiver();
    IntentFilter intentFilter = new IntentFilter();  
    intentFilter.addAction("android.intent.action.HEADSET_PLUG");  
    registerReceiver(headsetPlugReceiver, intentFilter);  
  }  

  @Override  
  public void onDestroy() {  
    unregisterReceiver(headsetPlugReceiver);  
    super.onDestroy();  
  } 
}  

如上这样就可以实现检测耳机插入和拔出了。

参考:http://outofmemory.cn/code-snippet/970/android-detect-user-shifou-cha-erji