Android Question abandonAudioFocus and AudioFocusRequest.Builder


New Member
Licensed User
With this code I can recover audio focus (sdk 30). But how do you abandon the audio focus?

This code does not work :

jo.RunMethod("abandonAudioFocus", Array(event)) or jo.RunMethod("abandonAudioFocusRequest", Array(event))

I need to create an AudioFocusRequest with AudioFocusRequest.Builder but I have no java knowledge to do it in B4A.

Someone can help me ?

Thanks for your help.

Dim jo As JavaObject
jo = jo.RunMethod("getSystemService", Array("audio"))
Dim event As Object = jo.CreateEventFromUI("", "audio", Null)
Dim p As Phone
jo.RunMethod("requestAudioFocus", Array (event, p.VOLUME_MUSIC, 2))) '2 = AUDIOFOCUS_GAIN_TRANSIENT


B4X founder
Staff member
Licensed User
Longtime User
Please use [code]code here...[/code] tags when posting code.

This code should work on Android 8+ (SDK 26+):
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private AudioFocusRequest As JavaObject
    Private AudioManager As JavaObject
End Sub

Public Sub Initialize
'    B4XPages.GetManager.LogEvents = True
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
End Sub

Private Sub CreateAudioFocusRequest (RequestType As String) As Boolean
    Dim AudioManagerStatic As JavaObject
    Dim ctxt As JavaObject
    AudioManager = ctxt.RunMethod("getSystemService", Array("audio"))
    Dim event As Object = AudioManager.CreateEventFromUI("", "audio", Null)
    Dim builder As JavaObject
    builder.InitializeNewInstance("", Array(AudioManagerStatic.GetField(RequestType)))
    builder.RunMethod("setOnAudioFocusChangeListener", Array(event))
    AudioFocusRequest = builder.RunMethod("build", Null)
    Dim res As Int = AudioManager.RunMethod("requestAudioFocus", Array(AudioFocusRequest))
    Return res = 1 'granted
End Sub

Sub audio_Event (MethodName As String, Args() As Object) As Object
    Return Null
End Sub

Private Sub AbandonAudioFocus
    If AudioFocusRequest.IsInitialized Then
        AudioManager.RunMethod("abandonAudioFocusRequest", Array(AudioFocusRequest))
    End If
End Sub

Private Sub Button1_Click
End Sub
Upvote 0