Headphone Jack Listener Android

2019-02-14 03:41发布

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条回答
淡お忘
2楼-- · 2019-02-14 04:19

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

查看更多
登录 后发表回答