This tutorial covers how to handle the back button on an Android app created with Godot Engine. By default Godot handles the back button on Android automatically and will quit out of your application when the back button is pressed. This needs to be disabled in the project settings or manually via GDScript to handle the back button differently.
Disable Through Project Settings
Open the project settings and search for quit
. Then ensure the Quit On Go Back
option is not checked as seen below.
Disable Through GDScript
To disable quitting when the back button is pressed via GDScript, call the
set_quit_on_go_back()
method on the scene tree.
func _ready() -> void:
get_tree().set_quit_on_go_back(false)
To resume quitting when the back button is pressed, call the same method with
true
.
func _ready() -> void:
get_tree().set_quit_on_go_back(true)
Handling the Back Request
Once the automatic quitting functionality is disabled by one of the two methods above, it is possible to handle the back button notification and perform a different action instead. For instance, you may want to go back to the previous scene or close a popup window.
This is easily done by handling the NOTIFICATION_WM_GO_BACK_REQUEST
notification inside of the _notification()
function.
func _notification(what: int) -> void:
match what:
MainLoop.NOTIFICATION_WM_GO_BACK_REQUEST:
# Handle Android back button
handle_back_button()