Nitzan Tomer
Nitzan Tomer

Reputation: 164367

When earphones are plugged in don't play notification sound through the speakers

I'm adding sound to certain notifications in my app, like so:

Notification notification = ...
...
notification.sound = Uri.parse(...);

When the notification sound plays it does so through the speakers even when headphones are plugged to the phone, and so the sound is played in both the speakers and headphones.

Is there a way to play the sound only through the headphones if it's plugged in?

Upvotes: 3

Views: 8307

Answers (2)

N J
N J

Reputation: 27535

Is there a way to play the sound only through the headphones if it's

plugged in?

For now its not possible to forcefully play sound through headphones

see this google issue tracker Notifications are played through external speaker when headphones are plugged in and discussion.


For checking headphone is plugged in

Register Receiver

ReceiveBroadcast receiver=new ReceiveBroadcast();       
registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));

onReceive() code

public void onReceive(Context context, Intent intent) {
     if (intent.hasExtra("state")){
         if (headsetConnected && intent.getIntExtra("state", 0) == 0){
             headsetConnected = false;
            
         } else if (!headsetConnected && intent.getIntExtra("state", 0) == 1){
            headsetConnected = true;
         }
     }
 }

Upvotes: 4

Rajesh Satvara
Rajesh Satvara

Reputation: 3964

You can use AudioManager.isWiredHeadsetOn() for checking if the headset are plugged in.

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

example :

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

Upvotes: 0

Related Questions