How to handle the back key pressed event on Android device?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By alexzheng

Tried the following code, there is no InputEventKey at all when pressed the soft back key.

func _input(event):
if event is InputEventKey: #and event.scancode == KEY_BACK and event.is_pressed():
_on_Back_pressed()

:bust_in_silhouette: Reply From: mokalux

hello there,

func _ready():

	get_tree().set_auto_accept_quit(false)
	pass



func _notification(what):
	if (what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST):
		# => DO THINGS HERE <= 
		pass

Hope this helps. At least that’s the way it works with godot 2.1.x

PEACE.

EDIT as per comment from Calinou it should work with godot 3.x.

In your menu scene:

func _ready():
	get_tree().set_auto_accept_quit(true)
	pass

So when you press back it exits the app.

In your other scenes (for example level01):

func _ready():
	get_tree().set_auto_accept_quit(false)
	pass

func _notification(what):
	if (what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST):
		get_tree().change_scene("res://scenes/menu.tscn")

In order to go back to menu scene.

Hope this helps.

it won’t woks in 3.0, use set_quit_on_go_back instead to stop quit.
I just want to catch the KEY_BACK event in Android to go back to the preview scene, I do not know how to do it.

The MainLoop.NOTIFICATION_WM_QUIT_REQUEST notification can handle the back key on Android, but since there is a KEY_BACK constant, there must be some way to catch it.

alexzheng | 2018-06-02 10:18

after setquitongoback(false), no MainLoop.NOTIFICATION_WM_QUIT_REQUEST is triggered at all.

alexzheng | 2018-06-02 10:25

See also Handling quit requests in the Godot documentation.

Calinou | 2018-06-02 21:18

please see edit in my answer.

mokalux | 2018-06-03 00:21

Thanks for your reply.
I knows how to do it in 2.x,but it’s not working in 3.x ,

alexzheng | 2018-06-03 06:48

that’s weird as per the doc it should work the same. Hope someone guides you in the right direction.

I haven’t switched to godot 3.x yet.

mokalux | 2018-06-03 14:29

Thank you anyway.

In 3.0 handle the MainLoop.NOTIFICATION_WM_GO_BACK_REQUEST notification instead.

alexzheng | 2018-06-05 03:38