如何获得AsyncTask的取消本身,当活动结束 [英] How to get an AsyncTask to cancel itself when the activity finishes

查看:171
本文介绍了如何获得AsyncTask的取消本身,当活动结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在开发一个ListActivity,有一堆列表中的每个项目显示的信息。
由于收集数据到列表(缩略图从DB SD卡和计数)的每个条目显示是耗费时间我想过使用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.

我想过使用的意见标签在我进入取消正在滚动关闭屏幕后重新使用的条目的AsyncTasks。
是这样的:

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();
    [...]
}

这部分应该工作,但我的问题是,当活动结束,或者用户改变方向。我宁愿避免保持一个数组或我AsyncTasks哈希映射只是为了能够取消他们都在的onPause或的onStop。
从阅读我做网页的AsyncTasks将继续后方向改变或活动结束,并在后台运行,即使最坏的情况将保持活动活着$ P $被垃圾收集pventing它(这绝对不是我想要的。)

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.)

我如何能做到这一点?
任何意见或建议, 我应该使用别的东西比AsyncTasks?

Any ideas or suggestions on how I could do this ?
Should I use something else than AsyncTasks ?

推荐答案

我会考虑一个的AsyncTask 的AsyncTask 的S数组code>。 <一href="http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate%28Progress...%29"相对=nofollow> onProgressUpdate 可以帮助这里。

I'd consider replacing array of AsyncTasks with one AsyncTask. onProgressUpdate could help here.

这篇关于如何获得AsyncTask的取消本身,当活动结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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