I have an Activity that starts an AsyncTask. The activity is allowed to show in Portrait or Landscape orientation. When the orientation is
I found a somewhat satisfying solution, which I want to share.
The method onRetainNonConfigurationInstance() is called only when the Activity is being recreated. More specifically: Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration.
I override this method and store a flag (stating whether it has been called or not). Then in onDestroy (called shortly after) I check this flag and if it's false I cancel the background task, because the Activity is being destroyed for good. If it's true this means that onRetainNonConfigurationInstance() has been called, which means that the Activity is being recreated, so I leave the task running.
I would have liked a better solution, but could not find such. The problems with this solution are two: the method is deprecated; there is no guarantee that the method will be called (according to the documentation). In practice the solution works for me, so I'll use it...