This article translated from: http://developer.android.com/training/managing-audio/audio-output.html
You can have many options when using Android devices to play audio. Most devices have built-in speakers, wired headphones, and many devices that support Bluetooth and a2dp audio.
Check the audio playing hardware used
Your application behavior will be affected by the hardware of the output audio.
You can use the following code to query the audiomanager object and determine whether the current audio output hardware is a device speaker, a wired headset, or a bluetooth device connected to the device.
If (isw.tha2dpon ()){
// Adjust output forbluetooth.
} Else if (isspeakerphoneon ()){
// Adjust output forspeakerphone.
} Else if (iswiredheadseton ()){
// Adjust output forheadsets
} Else {
// If audio plays andnoone can hear it, is it still playing?
}
Process changes in audio output hardware
When the headset is unplugged or the bluetooth device is disconnected, the audio stream is automatically routed to the built-in speaker. If this happens when you listen to music at a high volume, the sound will become noisy and surprising.
Fortunately, the system will issue an intent object of the actiion_audio_becoming_noisy type when this happens. Registering a broadcastreceiver object that listens to this intent object is a good practice when playing audio. When playing a music, you usually want to pause the playing, while when playing a game, you want to reduce the volume.
Privateclassnoisyaudiostreamreceiverextendsbroadcastreceiver {
@ Override
Public void onreceive (context, intent ){
If (audiomanager. action_audio_becoming_noisy.equals (intent. getaction ())){
// Pause the playback
}
}
}
Private intentfilter = new intentfilter (audiomanager. action_audio_becoming_noisy );
Private void startplayback (){
Registerreceiver (mynoisyaudiostreamreceiver (), intentfilter );
}
Private void stopplayback (){
Unregisterreceiver (mynoisyaudiostreamreceiver );
}