Today's #AndroidDev #Protip by +Kristan Uccello is about being a good audio citizen.

A big part of being a good audio citizen on Android and providing expected audio behaviour for users is respecting audio focus to make sure that apps don't play audio over each other unexpectedly.

Playing audio in your app takes more than just instantiating a MediaPlayer and feeding it an audio source file. Before using the audio system, an app should request audio focus and assert that audio focus has been successfully granted to it. Note that it is NOT a good practice to simply request audio focus when your app starts. Instead, request focus as close as possible to the event or call that will actually use the audio system.

The APIs for audio focus are fairly simple. Apps can request audio focus from the AudioManager by calling requestAudioFocus [1] with an OnAudioFocusChangeListener and one of the "duration hint" [2] options describing whether this is for long-form or short-form (transient) audio playback. To abandon audio focus, simply call abandonAudioFocus. Note that the audio focus change listener has corresponding AUDIOFOCUS_GAIN and AUDIOFOCUS_LOSS events for the various duration hints.

For more details on properly handling audio focus, check out our new blog post on the topic here:

Respecting Audio Focus:

As well as the relevant Android Training class:

Managing Audio Focus:


[1] requestAudioFocus:
Shared publiclyView activity