Android implements multi-threaded downloading of files (supports pause, cancellation and breakpoint continuation)

Multi thread downloading of files (supports pause, cancel and breakpoint continuation)

Multiple threads download files at the same time, that is, multiple requests are initiated for the same request address through multiple threads at the same time, and the data to be downloaded is divided into multiple parts. At the same time, each thread is only responsible for downloading some of them, and finally the downloaded parts of each thread can be assembled.

Knowledge and problems involved

1、 How is the requested data segmented

First, request the total file size through httpurlconnection, then calculate the download amount of each thread according to the number of threads, and allocate it to each thread to download

2、 How to download after segmentation and how to assemble after downloading

After segmentation, set the range parameter to the request header of each thread. It allows the client to request only part of the data of the file, and each thread only requests to download the data within the corresponding range. The target file range can be assembled by writing it into the same file using RandomAccessFile (random read-write file). It is a new header field in http / 1.1, It allows clients to actually request only a portion of the document (ranges can overlap each other)

Range usage:

Set request header in httpurlconnection

3、 Implementation of pause download and resume download (use of wait(), notifyall(), synchronized)

Just remember five things about synchronized:

For wait(), notify(), notifyall(), please note that

4、 Implementation of canceling download and resuming at breakpoint

Canceling the download means canceling the execution of each thread. It is not recommended to directly use the thread. Stop () method. Safely canceling the thread means that the execution of the run method ends. As long as you control the loop, you can end the run method, that is, the thread

Breakpoint continuation is actually the same as downloading again, but the file size and the starting and ending positions of each thread are not recalculated. Instead, the current position and end position saved by each thread when the download was cancelled last time, so that each thread can continue to download next to the last place

Corresponding permissions need to be added for network access and reading and writing SD cards

All the code is pasted below, with detailed comments downloadfile. Java

Use in mainactivity

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>