Activity 是因为方向改变还是因为应用程序关闭而被销毁? [英] Is the Activity being destroyed because orientation changed or because app is closing?

查看:18
本文介绍了Activity 是因为方向改变还是因为应用程序关闭而被销毁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Activity 可以启动一个 AsyncTask.允许活动以纵向或横向显示.当方向改变时,Activity 被销毁并重新创建.无论方向改变多少次,任务都会继续工作.它还成功地将结果返回给活动(根据此处的 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. 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() 中,您传递任何任意对象返回系统('this' 是一个合理的选择).然后,在您的 onCreate() 方法中,您调用 getLastNonConfigurationInstance() 获取之前保存的对象.这使您可以非常快速、轻松地从先前的调用中恢复您的状态.我相信即使是正在运行的线程和打开的套接字也可以通过这种方式传递.

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.

这篇关于Activity 是因为方向改变还是因为应用程序关闭而被销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆