In my Activity some external thing (service) need to be destroyed in onDestroy(). But I do not want this when configuration change happens (e.g. keyboard flips out) because it will be restored right away.
So the question is: how to distinguish whether onDestroy() is caused by say Back-key press or part of config change process?
after @CommonsWare's answer it would be pretty simple) something like:
@Override
onDestroy() {
if (mIsChangeConfig == true) {
mIsChangeConfig = false:
} else {
stopService();
}
}
@Override
onRetainNonConfigurationInstance() {
mIsChangeConfig = true;
}
Some device configurations can change during runtime (such as screen orientation, keyboard availability, and when the user enables multi-window mode). When such a change occurs, Android restarts the running Activity ( onDestroy() is called, followed by onCreate() ).
After `onDestroy()` is called, the OS knows that those resources are discardable, and it starts cleaning up that memory. Your activity may also be completely shut down if your code manually calls the activity's finish() method, or if the user force-quits the app.
onDestroy() is a method called by the framework when your activity is closing down. It is called to allow your activity to do any shut-down operations it may wish to do.
OnDestroy will be called directly from any call to finish() in onCreate, skipping over onStop. onDestroy can be left out after a kill when onStop returns. Starting with Honeycomb, an application is not in the killable state until its onStop() has returned; pre-honeycomb onPause was the killable state.
In Android 3.x (API Level 11), you can call isChangingConfigurations()
to see if the activity is being destroyed due to a configuration change.
Prior to that, override onRetainNonConfigurationInstance()
and set a boolean data member (e.g., isChangingConfigurations
) to true
, and check that data member in onDestroy()
.
This may do the trick for you (from How to distinguish between orientation change and leaving application android):
Use the Activity's isFinishing() method.
Sample code:
@Override
protected void onDestroy() {
super.onDestroy();
if (isFinishing()) {
// Do stuff
} else {
// It's an orientation change.
}
}
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