My favorite file manager (File Express) has a nice feature:
If you press the <Back> button normal the program will go back to the previous state. If you press it for 1 second or longer the program will terminate.
I mimicked this by using the Activity_KeyPress und _KeyUp events and a timer.
My Question: Is there something like an Activity_LongKeyPress event, similar to Button_LongClick? Or - in other words - is there a more elegant way?
You do not need to use a timer. Instead save the current time in a global variable (type Long) and then in KeyUp check whether more than a second passed.
the following Code works fine on my devices. Holding the Back_Key or pressing it twice finishes the application. Pressing the Back_Key once shows a Toastmessage ("Press again to finish.")
B4X:
Sub Globals
Dim KeyCode_Back_Pressed As Boolean
Dim KeyCode_Back_Time As Long
End Sub
Sub Activity_KeyPress (KeyCode As Int) As Boolean 'return true if you want to consume the event
Select Case Keycode
Case KeyCodes.KEYCODE_BACK
If KeyCode_Back_Pressed = True Then 'Back Key was already pressed
If DateTime.Now - KeyCode_Back_Time > 2000 Then 'Interval too long
KeyCode_Back_Pressed = False 'Expired
End If
End If
If KeyCode_Back_Pressed = False Then 'User presses Key_Back for the first Time
ToastMessageShow("Press again to finish",False) 'Show Toastmessage
KeyCode_Back_Pressed = True 'Remember Keystroke
KeyCode_Back_Time=DateTime.Now 'Store Time
Return True 'Consume the Event to prevent Application from Closing
Else
'Do not consume and let User exit Application
End If
Case Else
End Select
End Sub