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)