Detailed analysis of resumable download for Android 1

Source: Internet
Author: User

Detailed analysis of resumable download for Android 1

In Android, resumable download is used a lot. After reading the tutorial by Dr. Li fuming, I also have some knowledge about resumable download and share it with you.

First, the resumable download function description: users can download any resources from the network. The advantage of resumable download is that when users exit the application for some other reasons, however, some files are being downloaded at this time. When the user clicks this application again, we should not ask the user to download the file again, but continue to download the file from the last download completed, this is the breakpoint download function.

Implementation idea: to download resources from the network, you need to use the HTTP protocol (if the resource is relatively large, we recommend using socket, such as MB), you need to use multiple threads, android4.x and later do not allow access to the network in the UI thread. Therefore, we need to use multithreading, asynchronous tasks, volley, and so on, then, because the user needs to read the original download progress when exiting the application and then entering, we need to use the SQLite technology to save the download progress of each thread, each time it is used for re-entry, data can be read from the database and then transferred to the thread, starting from the location where it previously stopped downloading.

Below are some source code analysis:

This is MainActivity. java

Public class MainActivity extends Activity {/** download path text */private EditText pathText;/** download Result Display */private TextView resultView; /** click to Download button */private Button downloadButton;/** click to stop button */private Button stopbutton;/** display progress ssssbar */private progressBar ProgressBar; /** the role of hanlder is to send messages to the Message Queue bound to the thread where the Hander object is created * here is the Handler of the UI thread, which changes the progressBar, resultText */private Handler handler = ne W UIHander (); private final class UIHander extends Handler {public void handleMessage (Message msg) {switch (msg. what) {case 1: int size = msg. getData (). getInt ("size"); progressBar. setProgress (size); float num = (float) progressBar. getProgress ()/(float) progressBar. getMax (); int result = (int) (num * 100); resultView. setText (result + "%"); // progressBar reaches the maximum value. if (progressBar. getProgress () = progressBar. g EtMax () {Toast. makeText (getApplicationContext (), R. string. success, 1 ). show ();} break; case-1: // download failed Toast. makeText (getApplicationContext (), R. string. error, 1 ). show (); break ;}}@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main);/** initialize each UI */pathText = (EditText) this. findViewById (R. id. path); resultView = (TextView) this. f IndViewById (R. id. resultView); downloadButton = (Button) this. findViewById (R. id. downloadbutton); stopbutton = (Button) this. findViewById (R. id. stopbutton); progressBar = (ProgressBar) this. findViewById (R. id. progressBar);/** set the click Time */ButtonClickListener listener = new ButtonClickListener (); downloadButton. setOnClickListener (listener); stopbutton. setOnClickListener (listener);} private final class ButtonClickListener implements View. onClickListener {public void onClick (View v) {switch (v. getId () {/** Download button */case R. id. downloadbutton: String path = pathText. getText (). toString (); if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {File saveDir = Environment. getExternalStorageDirectory (); // get the Save path download (path, saveDir); // start download} else {// Toast error in memory card. makeText (getApplicationConte Xt (), R. string. sdcarderror, 1 ). show ();} downloadButton. setEnabled (false); // sets the Download button to unavailable stopbutton. setEnabled (true); // you can use break to set the stop Download button; // you can stop download case R. id. stopbutton: this. task. exit (); // exit download, that is, to stop the thread from downloadButton. setEnabled (true); // The Download button can be stopbutton. setEnabled (false); // The download stop button cannot use break;} private DownloadTask task; private void download (String path, File saveDir) {// run in the main thread task = new DownloadTask (path, saveDir); New Thread (task ). start ();}/** UI control screen re-painting (update) is handled by the main thread. If the value of the UI control is updated in the Child thread, the updated value is not repainted to the screen * You must update the UI control value in the main thread so that it can be displayed on the screen, the value of the UI control cannot be updated in the Child thread */private final class DownloadTask implements Runnable {private String path; private File saveDir; private FileDownloader loader; public DownloadTask (String path, File saveDir) {this. path = path; this. saveDir = saveDir;}/*** exit download */public void exit () {if (loader! = Null) loader. exit ();} public void run () {try {loader = new FileDownloader (getApplicationContext (), path, saveDir, 3); // enable three threads to download progressBar. setMax (loader. getFileSize (); // sets the maximum scale of the progress bar, which is the file length loader. download (new DownloadProgressListener () {public void onDownloadSize (int size) {Message msg = new Message (); msg. what = 1; msg. getData (). putInt ("size", size); // pass the downloaded length to the UI thread and display handler in progressbar. sendMessage (msg) ;}});} catch (Exception e) {e. printStackTrace (); handler. sendMessage (handler. obtainMessage (-1 ));}}}}}

Source code parsing: Handler is mainly used here. In the child thread, when the download progress changes, the UI thread is notified to update the ProgressBar and ResultView. By calling the download Method in the subdownloadtask thread, the download contains a loop that does not stop before the download is completed. The DownloadProgressListener object is passed in, and the listener can continuously detect the download progress changes and send messages. In this cycle, sub-threads can continuously send messages to the UI thread, and the UI thread updates components. In this way, the MainActivity is perfect.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.