JLouis
JLouis

Reputation: 284

Detect when application is closed

I want to know when the app is closed, because I need to erase a Database when the user shutdown the app, just in the moment when the user close the app is the right moment to erase the SQLite Database, how can I detect this?

Upvotes: 13

Views: 34800

Answers (3)

fvaldivia
fvaldivia

Reputation: 474

In the last activity you could add this in the onBackPressed method:

override fun onBackPressed() {
    super.onBackPressed()
    if(this is /*your activity*/ && isTaskRoot) {
        println("App closed by user")
    }
}

Upvotes: -1

Chris Stratton
Chris Stratton

Reputation: 40337

This is a flawed design idea, which reflects a misunderstanding of the system - when the process overall dies, it's dead, meaning your code is no longer running.

You can do some tracking and have the last onDestory()'d activity do the cleanup as a courtesy, but don't assume that it will always actually happen (the method is not always called). If having a stale copy is a problem, clean it up on the next run.

That said, you can try using the ndk to provide a handler for process termination signals, but still I wouldn't count on it working in all cases. The limited potential to gain any sound functionality from this would probably not justify the effort unless you are already familiar with the concepts involved.

And do not for a minute mistake cleaning up for a security mechanism, as the file is there while your app is running, and would remain if your app terminated in an unexpected way.

Upvotes: 22

jcxavier
jcxavier

Reputation: 2232

Supposing you don't finish() your main activity, clearing your database inside the onDestroy() method of that activity might be the closest of what you want to accomplish. As has been pointed in the comments, refer to http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle.

Upvotes: 8

Related Questions