1

I am working on one of the project which need to play sound simultaneously when headphone is connected.

I am using below code but no luck

AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_NORMAL); 
am.setSpeakerphoneOn(true);
शु-Bham
  • 952
  • 1
  • 7
  • 14
  • possible duplicate of [simultaneously using a headphone and speaker](http://stackoverflow.com/questions/14210696/simultaneously-using-a-headphone-and-speaker) – KevinDTimm Jun 15 '15 at 14:32

1 Answers1

1

You need to use a BroadcastReceiver to handle the action sent when the headset is plugged. You need after that to check if the action sent by the broadcast equals Intent.ACTION_HEADSET_PLUG in the onReceive method, then you can play your sound using MediaPlayer

@Override 
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
        int state = intent.getIntExtra("state", -1);
        switch (state) {
        case 0:
            //Headset is unplugged
            break;
        case 1:
            //Headset is plugged
            MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);   
            mediaPlayer.start();
            break;
        default:
            Log.d(TAG, "I have no idea what the headset state is");
        }
    }
}

Please see this answer https://stackoverflow.com/a/13610712/2354845

Community
  • 1
  • 1
Badr
  • 2,021
  • 1
  • 21
  • 27