Simple code for Android download tool

Downloading should be a necessary function of every app. If we don't use a third-party framework, we need to implement the download tool ourselves. What can we do if we implement it ourselves?

First, if the server file supports breakpoint continuation, the main function points we need to implement are as follows:

Multithreading, breakpoint resume Download Management: start, pause, continue, cancel, restart

If the server file does not support breakpoint continuation, it can only be downloaded by ordinary single thread, and can not be suspended or continued. Of course, in general, server files should support breakpoint continuation!

The following are the renderings of single task download, multi task list download and Service Download:

single_ task

task_ manage

service_ task

Basic implementation principle:

Next, let's look at the specific implementation principle. Since our download is based on okhttp, we first need an okhttpmanager class to encapsulate the most basic network requests:

This class includes basic timeout configuration, initiating asynchronous requests according to breakpoint information, verifying whether server files are updated, HTTPS certificate configuration, etc. In this way, the network request part is available.

Next, we also need the support of the database to record the basic information of the downloaded file. Here we use SQLite with only one table:

Of course, there are also corresponding table addition, deletion, modification and query tool classes. For details, please refer to the source code.

Since download management is required, thread pool is also essential to avoid creating too many sub threads and achieve the purpose of reuse. Of course, the size of thread pool can be configured according to requirements. The main codes are as follows:

Next is our core download class filetask, which implements the runnable interface so that it can be executed in the thread pool. First, look at the logic of the run () method:

If the downloaded target file, the temporary file recording the breakpoint and the database record all exist, we first judge whether the server file has been updated. If there is no update, we will directly start the download according to the previous record, otherwise we need to prepare before the breakpoint download. If not all the record files exist, you need to judge whether to support breakpoint renewal. If so, follow the breakpoint renewal process. Otherwise, ordinary download is adopted.

First, let's take a look at the preparerangefile() method. Here, we will prepare for breakpoint continuation:

The first is to clear the history and create new target files and temporary files. Childtaskcount means that the file needs to be downloaded through several subtasks, so that the task size of each subtask can be obtained, and then the specific breakpoint information can be obtained and recorded in the temporary file. For file download, we use mappedbytebuffer class, which is more efficient than RandomAccessFile. Executing the OnStart () method at the same time will represent the preparation phase of the download. The details will be described later.

Next, look at the saverangefile () method:

This is to initiate an asynchronous request for the number of childtaskcounts according to the breakpoint information saved in the temporary file. If the response is successful, save the file in segments through the startsaverangefile() method:

Write the current file in the while loop and save the current downloaded location to the temporary file:

At the same time, call onprogress () method to send the progress, in which the while loop needs to be interrupted for canceling, exiting, saving records and pausing.

Because the download is performed in the sub thread, but we generally need to update the UI according to the download status in the UI thread, we send the status data of the download process to the UI thread through the handler: that is, call the handler. Sendemptymessage() method.

Finally, the filetask class also has a savecommonfile () method, that is, ordinary downloading that does not support breakpoint continuation.

We mentioned earlier that the status data of the download process is sent to the UI thread through the handler. Next, let's look at the basic processing of the progresshandler class:

In the handlemessage () method, we perform corresponding operations according to the current download status. If it is start, you need to insert the downloaded data into the database and execute initialization callback; If it is progress, execute the download progress callback; If it is cancel, delete the target file, temporary file, database record and execute the corresponding callback; If pause, update the database file record and execute the suspended callback; If it is finish, delete the temporary files and database records and execute the completed callback; If it is destroy, it means downloading directly in the activity. If you exit the activity, the database records will be updated; The last error corresponds to the error condition. Specific details can refer to the source code.

Finally, use the thread pool in the downloadmanager class to perform the download operation:

ThreadPool.getInstance().getThreadPoolExecutor().execute(fileTask);

And judge whether the newly added task is in the waiting state, which is convenient for processing in the UI layer. Here, the core implementation principle is over. For more details, please refer to the source code.

How to use:

Downloadmanager is a singleton class, which is encapsulated in specific usage operations. We can start, pause, continue, cancel, restart, thread pool configuration, HTTPS certificate configuration, query the record data of data, and obtain the data of a current download state according to the URL:

There are three ways to start a download task: 1. Through the start (downloaddata downloaddata, downloadcallback, downloadcallback) method of downloadmanager class, data can set the URL, save path, file name and number of subtasks: 2. Execute setondowloadcallback of downloadmanager class first (downloaddata, downloaddata, downloadcallback downloadcallback) method, bind data and callback, and then execute the start (string URL) method.

3. Chain calls need to be made through the dutil class: for example

The start () method will return an instance of the downloadmanager class. If you don't care about the return value, you can also get an instance of the downloadmanager class by using downloadmanager. GetInstance (context) for subsequent pause, continue, cancel and other operations.

For callback, you can use the downloadcallback interface to implement a complete callback:

You can also use the simpledownloadcallback interface to implement only the callback methods you need.

Pause the task in download: pause (string URL)

Resume suspended task: resume (string URL) PS: files that do not support breakpoint continuation cannot be suspended and resumed.

Cancel task: cancel (string URL), which can cancel the task being downloaded, or suspended.

Restart Download: restart (string URL). Suspended, downloading, cancelled and completed tasks can restart download. Download data saved: Destroy (String URL) and destroy (String... URLs), such as downloading directly in Activity, and can be invoked in onDestroy () method directly to save data. Configure thread pool: settaskpoolsize (int corepoolsize, int maxpoolsize), set the number of core threads and bus processes. Configure okhttp certificates: setcertificates (InputStream... Certificates) query single data in the database downloaddata getdbdata (string URL), query all data: List < downloaddata > getalldbdata() PS: the database does not save the downloaded data, and obtain a file data in the download queue: downloaddata getcurrentdata (string URL) Here is the basic introduction. More details and specific uses are in the demo. Please give more advice on unreasonable places.

GitHub address: https://github.com/Othershe/DUtil

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
分享
二维码
< <上一篇
下一篇>>