Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 545
StackOverflowed Avatar asked Nov 07 '12 16:11

StackOverflowed


People also ask

Can two apps use mic at the same time Android 11?

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.

How do I add music to Android studio?

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.


1 Answers

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;
   }
}
like image 180
iTech Avatar answered Sep 27 '22 18:09

iTech