Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish whether onDestroy() is called as part of configuration change sequence?

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; 
}
like image 676
Mix Avatar asked Jul 16 '11 10:07

Mix


People also ask

Is onDestroy () called when a configuration change occurs Why or why not?

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() ).

What happens when onDestroy is called?

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.

What is onDestroy () activity?

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.

What is the difference between onStop and onDestroy?

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.


2 Answers

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().

like image 103
CommonsWare Avatar answered Sep 28 '22 10:09

CommonsWare


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.
  }
}
like image 39
German Latorre Avatar answered Sep 28 '22 09:09

German Latorre