首页 > 其他分享 >【android】android-检测耳机的插入和拔出动作

【android】android-检测耳机的插入和拔出动作

时间:2023-03-07 15:36:42浏览次数:55  
标签:Toast 耳机 headset void 插入 intent import android

在android系统中,检测耳机的插入和拔出,也是通过广播实现的,可以建立一个Broadcast Receiver 监听"android.intent.action.HEADSET_PLUG" 这个Intent。

在这个Intent中包含以下几个值:


state ---       0代表拔出,1代表插入
name--- 字符串,代表headset的类型。
microphone --   1代表这个headset有麦克风,0则没有。

在使用的时候发现直接在AndroidManifest,xml文件中静态注册是无效的<receiver android:name=".HeadsetPlugReceiver"> <intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" android:enabled="true"> </action>
</intent-filter>
</receiver> 解决办法是在代码中动态注册。

import android.app.Activity;import android.content.IntentFilter;
import android.os.Bundle;

public class HeadSetActivity extends Activity {
    HeadsetPlugReceiver headsetPlugReceiver; 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        registerHeadsetPlugReceiver();
    }
    private void registerHeadsetPlugReceiver(){
        headsetPlugReceiver  = new HeadsetPlugReceiver ();
        IntentFilter  filter = new IntentFilter();
        filter.addAction("android.intent.action.HEADSET_PLUG");
        registerReceiver(headsetPlugReceiver, filter);
    }
@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    unregisterReceiver();  //注销监听
}
private void unregisterReceiver(){
    this.unregisterReceiver(headsetPlugReceiver);
}
}

在broadcast Receiver中监听事件:

<pre name="code" >

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class HeadsetPlugReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

      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();
        }
      }
  }

}

【参考连接】

Android 实时监听耳机拔除

 

标签:Toast,耳机,headset,void,插入,intent,import,android
From: https://www.cnblogs.com/opensmarty/p/17188243.html

相关文章