Android Question Back button code

aaronk

Well-Known Member
Licensed User
Longtime User
Hello,

I have come across a small issue where I want to stop the back button from going back to the previous activity.

I have been using the following code to do this:

B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean
   If KeyCode = KeyCodes.KEYCODE_BACK Then
      Return
   End If
End Sub

However the above code didn't work and it just closed my activity and loaded the previous activity.

I then searched the forum and found some code that Erel posted:

B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean
  Select KeyCode
    Case KeyCodes.KEYCODE_BACK
      Return True
  End Select
  Return False
End Sub
This code works fine.

However I did notice that Erel posted 'I see it too. This will be fixed in the next update.' however I am not sure if I have done something wrong in my code or if this hasn't been fixed in v3.00 (as this is the version I am using)?
http://www.b4x.com/android/forum/threads/android-4-3-pb-with-closing-the-app.31328/

I have the same issue on Android my Samsung Galaxy S2 (running Android 2.3.6) and on my Sony Xperia Z (running Android 4.2.2).

However to get past this issue I had to use the code above (2nd lot of code above) to fix this issue.

Through I would share this in case someone else gets the same issue. (unless I am doing something wrong and the 1st lot of code shouldn't of worked?)
 

Informatix

Expert
Licensed User
Longtime User
(unless I am doing something wrong and the 1st lot of code shouldn't of worked?)

Yes the 1st code is wrong. The function expects that you return a boolean (there's "As boolean" at the end of the first line). So writing "return" only is not enough. A "Return True" or "Return False" is expected. "Return" alone returns an empty string so the interpretation by the code behind cannot be predicted (in this case, it interprets this empty string as False).
 
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
@Erel - The app doesn't crash but just goes back a screen (activity), it's like it ignores the code in that sub but if I write to the log when the back button is pressed (write to the log just before the return) it will log it. Looks like it ignores the 'return' in that sub.

@Informatix - I think you might be right, did notice the 2nd lot of code has 'return true' where my 1st lot of code doesn't have that.
 
Upvote 0

elitevenkat

Active Member
Licensed User
Longtime User
<code>
Sub Activity_KeyPress(KeyCode As Int) As Boolean
Dim Answ As Int
If KeyCode=KeyCodes.KEYCODE_BACK Then
Answ=Msgbox2("Do you want to quit the program ?","A T T E N T I O N","Yes","","No",Null)
If Answ=DialogResponse.NEGATIVE Then
Return True
Else
Activity.Finish
Return False
End If
End If
End Sub
</code>
The above code works fine.
 
Upvote 0
Top