Headphone Jack Listener Android

天大地大妈咪最大 提交于 2019-12-19 02:48:28

问题


Does anyone know how I can detect if the headphone jack on a device is unplugged on Android? I have a music player and I need to pause the music when the headphones are unplugged. The closest thing I have found is using the AudioManager. Is that the right direction to go?


回答1:


This is what I ended up doing:

private class NoisyAudioStreamReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
            pause();
        }
    }
}

private IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);

private void startPlayback() {
    registerReceiver(myNoisyAudioStreamReceiver(), intentFilter);
}

private void stopPlayback() {
    unregisterReceiver(myNoisyAudioStreamReceiver);
}

I found the answer at this link: http://developer.android.com/training/managing-audio/audio-output.html



来源:https://stackoverflow.com/questions/9985343/headphone-jack-listener-android

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