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?
When two apps are capturing concurrently, only one app receives audio and the other gets silence. Android shares the input audio according to these rules: If neither app is privacy-sensitive, the app with a UI on top receives audio. If neither app has a UI, the one that started capture the most recently receives audio.
Open your Android Studio and create a new project. Create a new folder named "raw" in your Android project's "res" folder and place your audio file inside the "raw" folder. You can see the audio is now successfully added into your Android Studio project by viewing the "raw" subfolder under "res" folder.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With