androidandroid-asynctaskandroid-activity

Is the Activity being destroyed because orientation changed or because app is closing?


I have an Activity that starts an AsyncTask. The activity is allowed to show in Portrait or Landscape orientation. When the orientation is changed, the Activity is destroyed and recreated. The task continues working no matter how many times the orientation is changed. It also returns the results to the activity successfully (according to CommonsWare's answer here https://stackoverflow.com/a/3821998).

What I want to achieve is: when the activity is destroyed because the application is closing - the task should be cancelled. However, when the activity is destroyed because of an orientation change - the task should NOT be cancelled.

Basically the question is how to distinguish between the two cases: application is closing / orientation change. In both cases the onDestroy() method is called and there is no easy way to check something like isChangingOrientation()...

P.S. I can also consider a totally different approach if necessary.


Solution

  • In general, you don't want to define onConfigurationChanged() because it's so hard to get everything right. The best approach is to let the app be killed and recreated when the orientation changes.

    To make the transition easier, you can implement onRetainNonConfigurationInstance(). This method will be called by the system when it knows that your app will be restarted almost immediately. In onRetainNonConfigurationInstance(), you pass any arbitrary object back to the system ('this' is a reasonable choice). Then, in your onCreate() method, you call getLastNonConfigurationInstance() to get the previously-saved object. This allows you to very quickly and easily restore your state from the previous invocation. I believe even running threads and open sockets can be passed across this way.

    See Save cache when rotate device for more info.