加载 Android UI 避免锁定
我正在为 Android 构建一个新闻阅读器,其中第一个 Activity 将显示最新新闻列表,并结合缩略图预览图像。 为了获取缩略图,我必须运行一个方法,这会大大增加加载时间;所以,我想创建一个单独的线程来每次运行。 更具体地说,我想先加载新闻标题,然后加载图片,一张一张;在执行所有这些操作时,我不希望 UI 被锁定(例如,如果用户触摸新闻,我希望应用程序加载它,即使有一些缩略图仍在加载)。 我的问题是:我应该使用处理程序(每个新闻一个线程)还是 AsyncTask(每个新闻一个 asyncTask 对象)来实现这一目标?
谢谢您的回复。
I'm building a news reader for Android, where the first Activity will show a list of the latest news, combined with a thumbnail preview image.
In order to get the thumbnail I have to run a method, which increase heavily the loading time; so, I was thinking to create a separate thread to run everytime.
More specifically I'd like to load the news titles first, and then load the pictures, one by one; while doing all this I don't want the UI to be locked (for instance, if an user touches a news I want the app to load it, even if thare are some thumbnails still loading).
My question is: should I use handlers (one thread for each news) or AsyncTask (one asyncTask object for each news) to achieve this?
Thank you for your replies.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Handler Vs AsyncTask
我会使用 asynctask 下载所有“新闻链接”,然后调用 asynctask一个异步任务,用于下载每个缩略图并在执行后更新 UI。然后,如果用户在完成之前单击链接,您可以在主 Asynctask 上调用 cancel,这将检查每个缩略图 asynctask 之间的 isCancelled() ,并在取消时返回。
Handler Vs AsyncTask
I would use an asynctask to download all the "news links" and then have that asynctask call an asynctask to download each thumbnail and update the UI onPostExecute. Then, if the user clicks a link before it is done, you could call cancel on the main Asynctask, which would check for isCancelled() between each thumbnail asynctask and would return if it was cancelled.
毫无疑问,AsyncTasks 比线程处理程序架构更加简化和模块化,但在内部它们以相同的方式执行操作。
谈到您的问题,我建议先加载新闻。
您的新闻 pojo/类可以包含两个字段,
title 和 imageUrl。
现在显示新闻列表并启动另一个 AsyncTask,逐一获取图像并将它们存储在 Data 中Str/list。
每次从服务器获取图像时,您的适配器都应该是“notifyDataSetChanged()”。
这样,您就可以让用户首先看到新闻,并且加载图像,而不会阻塞 UI。
No doubt that AsyncTasks are more simplified and modularized than the thread-handler architechture, but internally they perform the action in same way.
Coming to your problem, I would suggest that load the news first.
Your news pojo/class can be like containing two feilds,
title and imageUrl.
Now display the news list and start another AsyncTask that fetches the images one by one and store them in a Data Str/list.
your adapter should be "notifyDataSetChanged()" every time the image is fetched from server.
This way you are allowing user to see the news first, and the images are loaded without making UI get blocked.
我会创建异步任务来加载数据,然后在异步任务运行时执行一个填充列表的任务
i wit make asynch task for loading the data and then excute a task thats populate the list when the async task is don ore while it is running