Headphone Jack Listener Android

DRiFTy picture DRiFTy · Apr 3, 2012 · Viewed 7.7k times · Source

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?

Answer

DRiFTy picture DRiFTy · Apr 3, 2012

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