I doubt very much that there are any public APIs that can tell you which application is currently in focus.
You can track if your application has audio focus by requesting it, for example:
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 must ensure that your listener is a lone copy of your listener when you request and refuse focus, see my answer here to fix common problems with audio focus
Here is an example 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; } }
source share