android - Activity重建时如何重新获取文件下载进度
天蓬老师
天蓬老师 2017-04-18 09:53:27
0
3
417

做了一个下载文件的列表,用RecyclerView展示。点击下载某个文件,交由单独的下载类去处理(单例),下载类计算下载进度返回给UI进行更新。但是当用户点击返回按钮返回上一级的时候,下载线程没有停止,activity被销毁。重新进入此Activity的时候,RecylerView里的对象是通过网络新获取的,怎么设计才能让此时RecyclerView里的对象和下载类里的对象对应起来呢?否则无法实时更新进度及状态。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
左手右手慢动作

When this kind of logic processing involves object destruction and reconstruction, attention should be paid to decoupling. The object references should not be matched, but the data values ​​should be matched. Do not place network processing directly in Activity or RecylerView. For downloading, it is best to start a background service to manage your download thread, and then let the service communicate with the Activity. In this way, you don’t have to care about whether your object can correspond. You only need to care about the download progress reported by the service to you. value. As for the interaction between Service and Activity, there are too many tutorials and wheels on the Internet, so I won’t go into details.

小葫芦

Whether it comes with the systemDownloadManager还是自定义的下载组件, 一个文件下载都会有一个下载ID, 或者对应一个Uri. 值得一提的是, 系统自动的DownloadManagerthe download information is maintained through the database.

  1. With this premise, it is still not enough. We need to find a way to get the download progress of each file. This is related to the specific implementation of DownloadManager. Taking the system as an example, it seems that it only provides the Query interface, so we need to create a Background thread to query download progress in real time.

  2. Finally, we need to consider how to manage the correspondence between ID or Uri and RecyclerViewItemView.

The above 1 & 2 can be implemented by referring to some mainstream image asynchronous loading frameworks (such as github: nostra13/Android-Universal-Image-Loader).

p.s. If you think it’s too complicated, you can refer to github: erehmi/CountDownTask. (I shamelessly recommend my own project [face covering])

p.p.s. It is not recommended to directly notifyDataChanged() to refresh the entire list, the performance is too low.

左手右手慢动作

It is best to use service for this kind of downloading tasks

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template