android 判断耳机是否插入的几种方式

释放双眼,带上耳机,听听看~!

1.耳机插入和拔出时会发出广播ACTION_HEADSET_PLUG

 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
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();
}
}
}
}
}; 

0:无插入,1:耳机和话筒均插入,2:仅插入话筒

2.在目录下读取状态

 private static final String HEADSET_STATE_PATH = "/sys/class/switch/h2w/state";
nbsp;private boolean isHeadsetExists() {
char[] buffer = new char[1024];
int newState = 0;
try {
FileReader file = new FileReader(HEADSET_STATE_PATH);
int len = file.read(buffer, 0, 1024);
newState = Integer.valueOf((new String(buffer, 0, len)).trim());
}
catch (FileNotFoundException e) {
Log.e("FMTest", "This kernel does not have wired headset support");
}
catch (Exception e) {
Log.e("FMTest", "", e);
}
return newState != 0;
}

3.第二种比较麻烦,其实android提供一个接口


AudioManager localAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);  
boolean isHeadSetOn = localAudioManager.isWiredHeadsetOn();
if(!isHeadSetOn){
Toast.makeText(context, "请插入话筒", Toast.LENGTH_LONG).show();
return;
}

不要忘了加上权限

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

人已赞赏
Android文章

Android 面包屑导航效果源码、Android 各种侧边栏总结源码、Android开发人员轻松实现的玻璃状模糊效果……

2020-2-5 1:42:14

Android文章

Intel HAXM为Android 模拟器加速运行慢的方法

2020-2-5 5:04:04

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索