Search code examples
androidandroid-sdk-toolsandroid-audiomanager

How to tell when another app stops playing music on Android?


My game uses Android AudioManager to request audio focus and to know when another app takes audio focus. It also uses this function on Resume() to know that an app is playing music so that I can silence in-game music.

audioManager.isMusicActive()

These methods cover most of my needs, but I also need to know when another app that was playing music has stopped playing music or has been closed. When that happens I'd like to start playing my in-game music.

My Audio Focus callback doesn't get notified of this event, which is where I'd expect to be notified. And I can't use 'isMusicActive()' because it returns TRUE even when my app has music paused.

Is there some other way to tell when another app has stopped playing music?


Solution

  • I don't think the AudioManager system allows for this. When your app has audio focus, but another app requests it, there are two types of focus loss - transient and permanent. In the first case, the system will automatically return focus to your app once the other app is done with it (e.g. if it needs to play a notification sound).

    But for permanent loss (i.e. another app is taking control to play audio for an unknown amount of time) you don't get any notification once that app is done with it. And OnAudioFocusChangeListeners only inform you of changes to your own focus when you make a request - you can't use it to monitor other apps' focus.

    This seems to be the prescribed behaviour - from the docs on handling focus changes:

    Permanent loss of focus

    If the audio focus loss is permanent (AUDIOFOCUS_LOSS), another app is playing audio. Your app should pause playback immediately, as it won't ever receive an AUDIOFOCUS_GAIN callback. To restart playback, the user must take an explicit action, like pressing the play transport control in a notification or app UI.

    So you're not really supposed to be automatically playing audio like that, it's meant to be initiated by the user. You could possibly register an AudioPlaybackCallback and get information about the overall system audio (and only react to changes when you don't have audio focus) but it might be better to just give your users the ability to mute/unmute your music and sound effects, and let them control what's happening on their device.