简体   繁体   中英

How do I know when an Android app is launched and destroyed?

I need to run some code when an App is launched and when it completely exits (is destroyed). I am using onCreate and onDestroy but unfortunately screen orientation changes destroys and recreates the activity.

Take a look at Android Application http://developer.android.com/reference/android/app/Application.html

You can know when Application created (Application.onCreated)

BUT you can't know when Application destroyed. Application.onTerminate() is only for use in emulated process environments.

Every time the app launched the onCreate method of your launcher activity is called. So you have to put the desired code in onCreate method of the Launcher activity.

And to detect whether your app is destroyed or not you can override onDestroy method ( just like adding the onCreate ) from Override unimplemented method menu. And put the codes inside of this method that you want to be executed when the app will be destroyed.

You could try this, if your code can happen in the background (won't work if you need something to happen on the UI Thread):

Have your activity hold a reference to a thread you extended, let's call it MyThread operator.

In onCreate, do that:

if(operator==null){
    operator = new MyThread();
    operator.start();     
}

Then, in MyThread, put your code in the two methods run() and interrupt() .

When your activity gets recreated through orientation change, it will keep the operator refence to your background thread. When you actually close your application, android will terminate your operator after some seconds and therefore execute your code.

Someone correct me please if I'm wrong, I haven't slept too long lately and threads always are a complicated topic...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM