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

后端 未结 6 1270
面向向阳花
面向向阳花 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:06

    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.

提交回复
热议问题