Check whether headphones are plugged in

↘锁芯ラ 提交于 2019-11-28 20:27:12
Naskov

You can use this code for checking if the headset is plugged in

AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.isWiredHeadsetOn();

(Don't worry about the deprecation, it's still usable for ONLY checking if the headset are plugged in.)

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

Available in Android 2.0 +

Use this code...

AudioManager am1 = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
Log.i("WiredHeadsetOn = ", am1.isWiredHeadsetOn()+"");
Log.i("MusicActive = ", am1.isMusicActive()+"");
Log.i("SpeakerphoneOn = ", am1.isSpeakerphoneOn()+"");

AudioManager.isWiredHeadsetOn() is DEPRECATED. So, you need to use AudioManager.getDevices() method instead:

private boolean isHeadphonesPlugged(){
        AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        AudioDeviceInfo[] audioDevices = audioManager.getDevices(AudioManager.GET_DEVICES_ALL);
        for(AudioDeviceInfo deviceInfo : audioDevices){
            if(deviceInfo.getType()==AudioDeviceInfo.TYPE_WIRED_HEADPHONES
                    || deviceInfo.getType()==AudioDeviceInfo.TYPE_WIRED_HEADSET){
                return true;
            }
        }
        return false;
    }

Use Google Awareness API

It's very rich in providing contextual feeling.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!