androidandroid-audiomanager

Android - is it possible to find out which app has audiofocus?


There's an app on my phone that keeps taking audio focus, even when no sound is playing. I'm wondering as an app developer if I'd be able to inform the user which app it is, or if I can tell if my app has audio focus?


Solution

  • I strongly doubt that there is any public APIs can tell you which app having the focus at the moment.

    You can keep track if your app has the audio focus by requesting it, e.g.:

    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    boolean requestGranted = AudioManager.AUDIOFOCUS_REQUEST_GRANTED == audioManager.requestAudioFocus(listener, AudioManager.STREAM_MUSIC,
                        AudioManager.AUDIOFOCUS_GAIN);
    if(requestGranted){
       // you now has the audio focus
    }
    

    You should make sure to maintain a single instance of your listener when you request and abandon focus, see my answer here to troubleshoot common problems with audio focus

    Here is an example of onAudioFocusChange():

    @Override
    public void onAudioFocusChange(int focus) {
    
      switch (focus) {
        case AudioManager.AUDIOFOCUS_LOSS:
            Log.d(TAG,"AUDIOFOCUS_LOSS");
            // stop and release your player
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            Log.d(TAG,"AUDIOFOCUS_LOSS_TRANSIENT");
            // pause your player
            break;
        case AudioManager.AUDIOFOCUS_GAIN:
            Log.d(TAG,"AUDIOFOCUS_GAIN");
            // restore volume and resume player if needed
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            Log.d(TAG,"AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
            // Lower volume
            break;
       }
    }