android - 与 AsyncTask 结合使用时处理 GridView 的并发

标签 android android-gridview

我正在阅读章节 processing bitmaps off the UI thread在安卓培训中。 在本章中,作者讨论了与 AsyncTask 结合使用时 GridView 的并发处理:

Common view components such as ListView and GridView introduce another issue when used in conjunction with the AsyncTask as demonstrated in the previous section. In order to be efficient with memory, these components recycle child views as the user scrolls. If each child view triggers an AsyncTask, there is no guarantee that when it completes, the associated view has not already been recycled for use in another child view. Furthermore, there is no guarantee that the order in which asynchronous tasks are started is the order that they complete.

对于上面这段,我有两个问题:

(1) GridView 的 subview 是什么? 以下图为例,是否每一个grid都是一个child view?

(2) 我对“如果每个 subview 都触发一个 AsyncTask,则不能保证它完成时,关联的 View 尚未被回收用于另一个 subview ”感到困惑。 任何人都可以解释更多细节吗?比如grid[1,1]触发了一个AsyncTask,当AsyncTask结束的时候,为什么会出现问题?

enter image description here

最佳答案

  1. 是的,每个网格项都是一个子项 View .

  2. AsyncTask 的主要目的正在处理脱离主线程的长时间运行的作业,因此 UI 不会挂起。在内部,一个 AsyncTask使用 ThreadPoolExecutor用固定数量的线程来管理任务。所以即使你开火二十AsyncTask s,一次只有少数几个会被执行。同时,由于每个AsyncTask在它自己的线程中运行,它可能随时完成,具体取决于系统决定如何安排您的线程。所以真的不能保证任务会以相同的顺序完成。

在脱离主线程处理图片时,还需要考虑以下场景。

AdapterView s,我们回收 subview ,这样我们就不需要初始化新的 View每次都是 View在屏幕上滚动。所以在这种情况下会发生一个 child View将触发 AsyncTask当图像出现在屏幕上时获取图像。

但是在获取图像之前,用户继续滚动并且 View 滚出屏幕并再次出现在另一侧(因为我们正在回收 View )。现在,它触发另一个 AsyncTask获取它应该显示的图像。同时,较早的AsyncTask与此 View 关联完成并设置此 View 的图像,即使它不是图像的正确位置。

关于android - 与 AsyncTask 结合使用时处理 GridView 的并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16343840/

相关文章:

java - 如何在每个 GridView 单元格中插入多个项目

android - 当 GridView 滚动时,它会更改其 View 的激活状态

.net - 如何将来自 .NET Web 服务的 DataSet 绑定(bind)到 Android GridView?

android - 通过 firebase 云消息传递将数据从 api 发送到我的应用程序

Android:使用 WebView.loadUrl 加载 JavaScript 但保留软键盘

android - 你如何调整 gradle 中 dex 内存的 jvm args?

android - 显示图像网格的最有效方式

java - 自定义 CursorAdapter 导致 GridView 性能滞后

java - 如何从android studio中的另一个模块导入类?

android - Android 模拟器上没有互联网 - 为什么以及如何修复?