是活动的破坏,因为方向变化,或者因为程序正在关闭?方向、程序

2023-09-12 22:18:19 作者:爱恨两茫茫.

我有一个活动启动一个的AsyncTask 。该活动允许纵向或横向显示。当方向改变时,活性被破坏并重新创建。任务继续无论取向多少次改变工作。它还结果返回到活动成功(根据CommonsWare的这里答案 http://goo.gl/WF1yW 的)。

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 http://goo.gl/WF1yW).

我想实现的是:当因为在应用程序关闭的活性被破坏 - 任务应该被取消。但是,由于方向变化的活动时被破坏 - 任务不应该被取消。

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.

基本上,问题是如何的区分这两种情况:应用程序被关闭/取向的变化。 在这两种情况下的onDestroy()方法被调用,有没有简单的方法来检查类似isChangingOrientation()...

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。我也可以在必要时考虑一个完全不同的方法。

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

推荐答案

在一般情况下,你不想来定义 onConfigurationChanged()因为它是如此难以得到的一切权利。最好的办法是让应用程序被杀死并重新创建时的方向变化。

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.

要进行工作交接,可以实现 onRetainNonConfigurationInstance()。此方法将被系统调用时,它知道你的应用程序将立即重新启动。在 onRetainNonConfigurationInstance(),你传递任意对象回系统('本'是一个合理的选择)。然后,在你的的onCreate()方法,你叫 getLastNonConfigurationInstance()获得previously保存的对象。这使您可以非常快速,轻松地从previous调用恢复状态。我相信,即使正在运行的线程和开放套接字可以在这种方式传递。

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.

请参阅保存缓存时旋转设备获取更多信息。