Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Service - onDestroy() method not called when using Force Stop

Tags:

android

When I stop a service using the stop button under the Running Services tab, the method onDestroy() is called.

But when I force stop the application, onDestroy() is never called.

Any explainations about this?

or maybe a solution to fire onDestroy() when force-stopped?

like image 248
user1732887 Avatar asked Dec 16 '12 18:12

user1732887


2 Answers

When your force stop an app, exactly that happens - It is Force Stopped. No warning, no callbacks, just stopped. The entire process is killed, and none of the running components (Activities, Services etc) are given any warning.

There is absolutely no guarantee that onDestroy() will be called. Move any application critical code into onPause(), which is called under most circumstances.

like image 68
Raghav Sood Avatar answered Nov 07 '22 15:11

Raghav Sood


From the documentation:

Once the activity is created, onPause() is the last method that's guaranteed to be called before the process can be killed... onStop() and onDestroy() might not be called. Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage.

To reiterate this point, Force Stop isn't intended to be graceful and exit the app in a caring manner. If you have critical code that must be run each time app finishes you need to run it in onPause().

like image 2
Sam Avatar answered Nov 07 '22 17:11

Sam