3
votes

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?

2

2 Answers

4
votes

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;
         }
     }
 }
0
votes

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();