Android Question Trapping Back Key in B4XPages ?

epiCode

Active Member
Licensed User
In my original project which did not use B4XPages I was able to trap back key by following code in Main Activity
Objective here is trap back key and close drawer if open else ask if user wants to exit without saving

Old Code - NO B4XPages:
Sub Activity_KeyPress (KeyCode As Int) As Boolean
  
    Select KeyCode
        Case KeyCodes.KEYCODE_BACK
            'close left drawer if open
            If Drawer.LeftOpen Then
                Drawer.LeftOpen = False
                Return True
            End If
                      
'''code to confirm exit 

            Activity.Finish
End Sub

After moving the project to B4XPages it is structured like this

In Activity Main:
Sub Activity_KeyPress (KeyCode As Int) As Boolean 'Return True to consume the event
    B4XPages.GetManager.RaiseEvent(B4XPages.GetManager.GetTopPage, "B4XPage_KeyPress", Array(KeyCode))
    Return False
End Sub

in B4XPage - (not B4XMainpage):
Sub B4XPage_KeyPress(KeyCode As Int) As Boolean

.... same code as above .....

End Sub

Now when the back key is pressed, the code still gets triggered but application is minimized/paused first
and results in following error

Log:
** Activity (main) Resume **
                                            <--- ((back key pressed))
** Activity (main) Pause event (activity is not paused). **
Error occurred on line: 1711 (B4XEdViewer)
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@2b8ac14 is not valid; is your activity running?
 
Last edited:

epiCode

Active Member
Licensed User
Code with Msgbox = broken code. Better not to post it in the forum.

The example handles the back key and closes the drawer: https://www.b4x.com/android/forum/threads/b4x-b4xpages-b4xdrawer.120246/#content
1. Removed Msgbox Code from example.

2. Using the code in example - My B4XPage_Keypress does not trigger - While it does trigger B4XPage_CloseRequest it gives me no 'Keycode" and no other alternate to intercept other keys like volume / play / pause.

I appreciate your help.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0
Top