用于取消 AsyncTask 的 ListAdapter 生命周期和屏幕旋转
我有一个异步任务,当视图通过 onDestoryView() 销毁时,我会取消该任务。这个问题是我做的“downloader.cancel(true);”并且它不会取消。事实上,它会返回 false。目前,它引用 ListAdapter 来向其中添加项目。但是,当我将屏幕转为横向时,ListAdapter 在 onPostExecute 期间为空。我无法弄清楚 ListAdapter 何时变为空。我尝试过 onDestory 和 onDestoryView 在 ListAdapter 变为 null 之前取消 asynctask,但它从来没有工作过。顺便说一句,这是在 ListFragment 内部。
目前,我只是检查异步任务中的适配器是否为空,但这确实让我很烦恼。我宁愿在 ListAdapter 为空之前取消任务。
有谁知道在屏幕旋转期间 ListFragment 的 ListAdapter 何时为空?
I have a asynctask that I cancel when the view is destoried via onDestoryView(). This problem is I do "downloader.cancel(true);" and it wont cancel. In fact, it will return false. Currently, it references the ListAdapter to add items to it. However when I turn the screen to landscape, the ListAdapter is null during the onPostExecute. I cannot figure out when the ListAdapter becomes null. I have tried both onDestory and onDestoryView to cancel the asynctask before the ListAdapter becomes null but it never works. This is inside of a ListFragment btw.
For the time being, I just check if the adapter is null in the asynctask but this really grinds my gears. I would rather just cancel the task before the ListAdapter is null.
Does anyone know when the ListAdapter is null for a ListFragment during screen rotations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
取消 AsyncTask 不会杀死线程。您将在 Thread 的文档中看到类似
stop 的方法
和destroy
未实现。因此,一旦 doInBackground 方法启动执行时,即使使用 取消(true)。您需要对其进行适当的编码。Cancelling an AsyncTask does not kill the Thread. You will see in the docs for Thread that methods like
stop
anddestroy
are unimplemented. So once the doInBackground method starts executing, it will run to completion even if the task is cancelled with cancel(true). You will need to code it appropriately.当屏幕方向更改时,默认行为是销毁 Activity 并重新创建它。因此 OnDestroy 和 OnCreate 方法将被调用。您可以取消此行为,在您的清单的活动中添加此行:
android:configChanges="keyboardHidden|orientation"
像这样:
您还需要在活动类中添加 onConfigurationChanged 方法。
之后,当方向改变时,OnDestroy 和 OnCreate 将不会被调用。
When the screen orientation is changed the default behavior is destroy the Activity and recreate it. So the methods OnDestroy, and OnCreate will be called. You can cancel this behavior adding this line in the activity that of your your Manifest:
android:configChanges="keyboardHidden|orientation"
Like that:
You also needs to add the method onConfigurationChanged in your activity class.
After that OnDestroy and OnCreate will not be called when orientation changes.