save data in android

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

I tried to do as they say in other answers, but I can’t do it. in windows open gives “0”, but on android nothing. I also tried to give permission when compiling to apk. in windows this work.

func _notification(what):
    if what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
	    save_data({score=score})


func _ready():
	score = load_data()['score']


func save_data(data: Dictionary) -> void:
	var file := File.new()
	file.open('user://save.data',  File.WRITE)
	file.store_var(data)
	file.close()


func load_data():
	var file := File.new()
	if file.file_exists('user://save.data'):
    	file.open('user://save.data', File.READ)
    	var data = file.get_var()
    	file.close()
    	return data
	return
:bust_in_silhouette: Reply From: davidoc

It looks like your score is not being saved when you quit because you are not listening to the correct notification, this is in the official docs:

On desktop platforms, the MainLoop has a special MainLoop.NOTIFICATION_WM_QUIT_REQUEST notification that is sent to all nodes when quitting is requested.

On Android, MainLoop.NOTIFICATION_WM_GO_BACK_REQUEST is sent instead. Pressing the Back button will exit the application if Application > Config > Quit On Go Back is checked in the Project Settings (which is the default).

(Edited to add format into the constants)

thanks, it works when the back button is pressed, but if I turn off the game by removing it from the list of open applications it does not work.

Timofey | 2021-03-31 15:42