Search code examples
androidprocesslifecycle

Life cycle of the application: How to do some clean jobs when the process is terminated?


My application is very straightforward, Main Activity -> activity 1 -> activity 2, and there is another worker thread who is doing some downloading jobs. And they are started within the same process.

I want the downloading thread is not terminated until all the activities are destroyed, or at the end of the process. In Java, it is very simple: it will be OK by adding some clean code in the main method. But I don't know what is the right way in Android. Because every activity is possible to be recycled by the system, I don't know where to put the clean code of the worker thread, and I also dont't know what is the end point of the total application.

Could anyone give me some ideas? thanks.


Solution

  • not sure if it helps, but you can start a service in your main activity and have all clean up code in the Service's onDestroy method. the service will be destroyed when your application will be destroyed

    onTerminate only works on emulator - it is stated in the docs.