如何让 AsyncTask 在活动完成时自行取消
我正在开发一个 ListActivity,它在列表的每个项目中显示大量信息。
由于收集要在列表的每个条目中显示的数据(来自 SD 卡的缩略图和来自数据库的计数)非常耗时,因此我考虑使用 AsyncTasks 来减轻主线程的负载并允许用户真正滚动列表快速无延迟。
我考虑过使用条目中视图的标签来取消滚动屏幕后重用的条目的 AsyncTasks。
类似于:
public void bindView(View view, Context context, Cursor cursor) {
[...]
MyAsyncTask t (MyAsyncTask) myImageView.getTag();
if (t != null) {
t.cancel(true);
t = null;
}
t = new MyAsyncTask();
myImageView.setTag(t);
t.execute();
[...]
}
该部分应该可以工作,但我的问题是当活动完成或用户改变方向时。我宁愿避免保留 AsyncTasks 的数组或哈希图,只是为了能够在 onPause 或 onStop 中取消它们。
根据我在网上所做的阅读,在方向更改或活动完成后,AsyncTasks 将继续在后台运行,最糟糕的是,它将使活动保持活动状态,防止其被垃圾收集(这绝对不是我想要的。
)关于如何做到这一点的想法或建议?
我应该使用 AsyncTasks 之外的其他东西吗?
I'm developing a ListActivity that has a bunch of information displayed in each items of the list.
Since gathering the data to display in each entry of the list (thumbnail from the SD card and counts from the DB) is time intensive I thought about using AsyncTasks to relieve the main thread from the load and allow the user to scroll through the list really fast without lagging.
I thought about using the tag of the views in my entry to cancel the AsyncTasks of the entries that are reused after scrolling off the screen.
something like:
public void bindView(View view, Context context, Cursor cursor) {
[...]
MyAsyncTask t (MyAsyncTask) myImageView.getTag();
if (t != null) {
t.cancel(true);
t = null;
}
t = new MyAsyncTask();
myImageView.setTag(t);
t.execute();
[...]
}
That part should work but my problem is when the activity finishes or the user changes orientation. I would rather avoid keeping an array or a hash map of my AsyncTasks just to be able to cancel them all in onPause or onStop.
From the reading I did on the web the AsyncTasks will continue running in the background after the orientation changes or the activity finishes and even worst it will keep the activity alive preventing it from being garbage collected (which is definitely not what I want.)
Any ideas or suggestions on how I could do this ?
Should I use something else than AsyncTasks ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会考虑用一个
AsyncTask
替换一组AsyncTask
。 onProgressUpdate 可以在这里提供帮助。I'd consider replacing array of
AsyncTask
s with oneAsyncTask
. onProgressUpdate could help here.