As the title says.
Specifically, I am writing an app that prints data to files over the course of runtime. I want to know when I can tell my PrintWriter
s to save the files. I understand that I can probably do autosave every X minutes, but I am wondering if Android Studio will let me save on close instead. I tried using onDestroy
but the code block never executed. (To be precise, I started the app, did a few things, closed the app, clicked Recents, and swiped the app away. The debugger showed that the app never got to that code.)
My current solution attempts to catch the surrounding circumstances by checking for key presses but this only works for the back and volume buttons and not the home, recent, or power buttons.
@Override public boolean onKeyDown(int key, KeyEvent event) {
close();
return false;
}
CodePudding user response:
There's a built in hook to the Activity lifecycle to save your state- onSaveInstanceState. There's even a bundle passed into you to save your state into for it to be restored (the matching function is onResumeInstanceState). And as a free bonus, if you call super.onSaveInstanceState and super.onRestoreInstanceState, it will automatically save the UI state of your app for all views with an id.
CodePudding user response:
please check the activity lifecycle : https://developer.android.com/guide/components/activities/activity-lifecycle
or if you're using fragment : https://developer.android.com/guide/fragments/lifecycle
I'm sure this 2 event will help your case :
override fun onStop() {
super.onStop()
}
or
override fun onPause() {
super.onPause()
}