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

后端 未结 6 1309
面向向阳花
面向向阳花 2021-01-01 21:12

I have an Activity that starts an AsyncTask. The activity is allowed to show in Portrait or Landscape orientation. When the orientation is

6条回答
  •  温柔的废话
    2021-01-01 22:12

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

提交回复
热议问题