Topic was automatically imported from the old Question2Answer platform.
Asked By
MeIsAHuman
Old Version
Published before Godot 3 was released.
Hello,
I’m trying to catch the back button on Android and use it to navigate back inside the game. Does anyone know which event is fired and how to prevent Godot from closing the game?
In versions 3.1 and above, just make a function without “mainloop.” Just make a transition to the scene that you consider to be the previous one and write this function:
func _notification(what):
if what == NOTIFICATION_WM_GO_BACK_REQUEST:
get_tree().change_scene_to_file("res://yourscene")
If you just want to prevent app from closing, you can use this:
get_tree().set_auto_accept_quit(false)
You can enable auto quit in the _ready() function of main menu and disable it in any button press functions so that game won’t quit by pressing back button unless you’re on the main menu.
For anyone who might be having issues with this: In Godot 3.0 rc1, checking for MainLoop.NOTIFICATION_WM_QUIT_REQUEST does not seem to work any more for Android (but works fine for Windows).
But checking for MainLoop.NOTIFICATION_WM_GO_BACK_REQUEST does the trick.
func _notification(what):
if what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
# For Windows
pass
if what == MainLoop.NOTIFICATION_WM_GO_BACK_REQUEST:
# For android
pass
Godot 3.0 also require this option to be unchecked: “Project→Project Settings→Quit On Go Back” as per #15189
AlexZ005 | 2018-03-05 21:32
Thank you, you saved me. I think this should be included in the documentation in order to avoid wasting time.
TGMG | 2020-05-26 18:08
Note that set_auto_accept_quit() and set_quit_on_go_back() on Android will not prevent the application from exiting if it is being closed from the opened windows panel.
GODOT 3.0:
I actually never got it to work with the code examples that have been given here, the only thing that worked for me was what AlexZ005 said in his comment to one of the previous answers:
Godot 3.0 also require this option to be unchecked: “Project→Project
Settings→Quit On Go Back” as per #15189
In the same menu there is also a checkbox to disable the ‘Auto accept Quit’.
func _notification(what):
if what == MainLoop.NOTIFICATION_WM_GO_BACK_REQUEST:
_on_Back_pressed()
if what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
_on_Back_pressed()
_on_Back_pressed() is my custom method
func _on_Back_pressed():
#Do what you want to do here
pass