I'm developing an android app using bluetooth communication (using a propetary protocol) and I need to catch the moment when the app is killed.
I wanted to use the "onDestroy()" method but it isn't called every time the app is killed. I noticed that it is called when I press the back button and, only sometimes, when I kill the app from the task manager.
The question is: How can I catch the moment before the app is killed?
Here is the code I tried to use:
@Override public void onDestroy() { sendMessage(msg); Log.d("SampleApp", "destroy"); super.onDestroy(); } @Override public void finish(){ sendMessage(msg); Log.d("SampleApp", "finish"); super.finish(); }
Unfortunately finish() is never called and onDestroy isn't called every time I close the app from the task manager.
How can I handle this?
Android app doesn't call "onDestroy()" when killed (ICS)
Android Activity onDestroy() is not always called and if called only part of the code is executed. Bookmark this question. Show activity on this post. onDestroy() is not always called.
You don't need to call stop( ) method. Android system automatically go thru those life cycle methods. But apparently onDestroy() always called after onStop() . If you want to kill activity just call finish() , it will destroy your activity.
This example demonstrates about How do I call OnDestroy Activity in Android app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.
As stated in the documentation here, there is no guarantee that onDestroy() will ever be called. Instead, use onPause() to do the things you want to do whenever the app moves into the background, and leave only that code in onDestroy() that you want run when your app is killed.
EDIT:
From your comments, it seems that you want to run some code whenever your app goes into the background, but not if it went into the background because you launched an intent. AFAIK, there is no method in Android that handles this by default, but you can use something like this:
Have a boolean like:
boolean usedIntent = false;
Now before using an intent, set the boolean to true. Now in your onPause(), move the code for the intent case into an if block like this one:
if(usedIntent) { //Your code }
Finally, in your onResume(), set the boolean to false again so that it can deal with your app being moved into the background by a non intent means properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With