Class AudioFocusManager

  • All Implemented Interfaces:

    
    public final class AudioFocusManager
    
                        

    A utility class to manage audio focus for an Android application. Ensures proper handling of audio focus requests, abandonment, and audio focus changes across different API levels (pre and post Android O).

    IMPORTANT: Uses application context to prevent memory leaks. Android's AudioManager may retain AudioFocusRequest references in its internal mAudioFocusIdListenerMap even after abandonAudioFocusRequest() is called, so using Activity context would cause Activity leaks.

    • Constructor Detail

      • AudioFocusManager

        AudioFocusManager(Context context)
    • Method Detail

      • requestAudioFocus

         final Boolean requestAudioFocus()

        Requests audio focus for the app. On Android O and above, it uses an AudioFocusRequest with specified audio attributes. On earlier API levels, it directly requests audio focus using AudioManager.

        Wraps AudioManager calls in try-catch to handle DeadSystemRuntimeException which can occur when the system audio service has died.

        Returns:

        true if audio focus is successfully granted, false otherwise.

      • abandonAudioFocus

         final Unit abandonAudioFocus()

        Abandons the currently held audio focus, ensuring the app no longer claims priority over audio playback. Compatible with both Android O+ (using AudioFocusRequest) and earlier versions.

        Wraps AudioManager calls in try-catch to handle DeadSystemRuntimeException which can occur when the system audio service has died.

        IMPORTANT: Must be called before nullifying audioFocusRequest to properly unregister the listener from AudioManager's internal map.

      • release

         final Unit release()

        Releases resources associated with the AudioFocusManager. This includes abandoning audio focus and nullifying listeners and focus requests.