reiley
reiley

Reputation: 3761

How to Stop musicplayer when I detach headphones?

I want to stop the currently running MusicPlayer when the user unplugs the headphones (both wired & bluetooth).

I came across sevral posts where use of:

isWiredHeadsetOn(), isBluetoothA2dpOn()

is suggested.

But Android docs says isWiredHeadsetOn() is deprecated. What alternative should I use?

Thanks

Upvotes: 3

Views: 2055

Answers (4)

user1777060
user1777060

Reputation: 273

I use AudioManager.ACTION_AUDIO_BECOMING_NOISY event in my app. Create your custom broadcast receiver:

private class HeadsetIntentReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context cntx, Intent intent) 
    {
        String action = intent.getAction();

        if(action.compareTo(AudioManager.ACTION_AUDIO_BECOMING_NOISY) == 0)
        {
        }
    }
};  /* end HeadsetIntentReceiver  */

Then register receiver:

headsetReceiver = new HeadsetIntentReceiver();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
mParentActivity.registerReceiver(headsetReceiver, mIntentFilter);

Don't forget to unregister it later.

Upvotes: 1

JohnP
JohnP

Reputation: 402

According to the documentation for it, it's deprecated but suggested to be used ONLY for checking to see if a headset is connected or not. Should be fine to use.

Upvotes: 0

Zach Lysobey
Zach Lysobey

Reputation: 15724

From the docs:

isWiredHeadsetOn() - This method is deprecated. Use only to check is a headset is connected or not.

It sounds like it is still recommended for what you're doing, though the docs are worded poorly

Upvotes: 2

John Kane
John Kane

Reputation: 4443

I just read a post where someone was suggesting registering for the ACTION_HEADSET_PLUG broadcast event.

You can apparently get the state of it from: intent.getIntExtra("state", 0));

Upvotes: 1

Related Questions