skip to Main Content

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 PrintWriters 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;
        
    }

2

Answers


  1. Please check the activity lifecycle:
    https://developer.android.com/guide/components/activities/activity-lifecycle

    Or if you’re using a fragment:
    https://developer.android.com/guide/fragments/lifecycle

    Consider using one of these two:

        @Override public void onStart() {
            super.onStart();
            close();
        }
    
        @Override public void onPause() {
            super.onPause();
            close();
        }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search