Android implementation of network multithreaded file download _android

Source: Internet
Author: User
Tags save file

Implementation principle

(1) First get the length of the download file, and then set the length of the local file.

(2) Calculate the data length and the download location of each thread according to the file length and number of threads.

For example: the length of the file is 6M, the number of threads is 3, then each thread download data length of 2M, each thread to start downloading the location as shown in the following figure:

(online looking for the map)

such as 10M size, using 3 threads to download,

Thread download length of data (10%3 = 0?) 10/3:10/3+1), 1th, 2 thread download length is 4M, the third thread download length of 2M

Download start Location: Thread id* The length of data downloaded per thread =?

Download End Location: (thread id+1) * The length of data downloaded per thread -1=?

Before the practice of a demo, not to say, directly on the code, the extension of the breakpoint, need to use the database, no longer added, there are many mature online projects can be used directly.

Instance

Mainapp:

Package Com.amos.app; 
Import Java.io.File; 
Import java.io.IOException; 
Import java.net.MalformedURLException; 
Import Java.net.URL; 
Import java.net.URLConnection; 
Import COM.AMOS.DOWNLOAD.R; 
Import Android.annotation.SuppressLint; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import android.os.Environment; 
Import Android.os.Handler; 
Import Android.os.Message; 
Import Android.util.Log; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.ProgressBar; 
Import Android.widget.TextView; 
Import Android.widget.Toast; /** * @author Yangxiaolong * @2014-5-6/public class Mainapp extends activity implements Onclicklistener {private 
Static final String TAG = MainApp.class.getSimpleName (); 
/** Display Download Progress TextView * * Private TextView Mmessageview; 
/** Display Download Progress ProgressBar * * Private ProgressBar Mprogressbar; 
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout. progress_activity); 
Findviewbyid (R.ID.DOWNLOAD_BTN). Setonclicklistener (this); 
Mmessageview = (TextView) Findviewbyid (r.id.download_message); 
Mprogressbar = (ProgressBar) Findviewbyid (r.id.download_progress); 
@Override public void OnClick (View v) {if (V.getid () = = r.id.download_btn) {dodownload (); }/** * Update UI interface information using Handler/@SuppressLint ("Handlerleak") Handler Mhandler = new Handler () {@Override public vo 
ID handlemessage (Message msg) {mprogressbar.setprogress (Msg.getdata (). GETINT ("size")); 
float temp = (float) mprogressbar.getprogress ()/(float) mprogressbar.getmax (); 
int progress = (int) (TEMP * 100); if (progress = =) {Toast.maketext (mainapp.this, "Download complete!") 
", Toast.length_long). Show (); 
Mmessageview.settext ("Download progress:" + progress + "%"); 
} 
}; /** * Download preparation, get SD card path, open thread/private void Dodownload () {//Get SD card path String path = Environment.getexternalstoragedirec 
Tory () + "/amosdownload/"; 
File File = new file (path); If the SD card directory does not exist create if (!file).Exists ()) {File.mkdir (); 
}//Set ProgressBar initialization mprogressbar.setprogress (0); For simplicity's sake, I'm going to write the URL and file name to death, but these can be obtained by httpheader to String DownloadURL = "http://gdown.baidu.com/data/wisegame/ 
91319A5A1DFAE322/BAIDU_16785426.APK "; 
String fileName = "baidu_16785426.apk"; 
int threadnum = 5; 
String filepath = path + fileName; 
LOG.D (TAG, "Download file path:" + filepath); 
Downloadtask task = new Downloadtask (DownloadURL, Threadnum, filepath); 
Task.start (); /** * Multithreaded File Download * * @author Yangxiaolong * @2014-8-7/class Downloadtask extends Thread {private String Downloa 
durl;//download link address private int threadnum;//Open thread number private String filepath;//save file path address private int blocksize;//Download amount per thread 
Public Downloadtask (string downloadurl, int threadnum, string fileptah) {this.downloadurl = DownloadURL; 
This.threadnum = Threadnum; 
This.filepath = Fileptah; 
@Override public void Run () {filedownloadthread[] threads = new Filedownloadthread[threadnum]; try {URL url = new URL (downloaDurl); 
LOG.D (TAG, "Download file http path:" + DownloadURL); 
URLConnection conn = Url.openconnection (); 
Read the total size of the download file int fileSize = Conn.getcontentlength (); 
if (fileSize <= 0) {System.out.println ("read file failed"); 
Return 
//Set ProgressBar maximum length for file size Mprogressbar.setmax (fileSize); Calculate the length of data downloaded per thread blockSize = (fileSize% threadnum) = = 0? 
Filesize/threadnum:filesize/threadnum + 1; 
LOG.D (TAG, "fileSize:" + fileSize + "blockSize:"); 
File File = new file (FilePath); for (int i = 0; i < threads.length i++) {//boot thread, download the part of each thread that needs to be downloaded separately threads[i] = new Filedownloadthread (URL, file, Blo 
Cksize, (i + 1)); 
Threads[i].setname ("Thread:" + i); 
Threads[i].start (); 
Boolean isfinished = false; 
int downloadedallsize = 0; 
while (!isfinished) {isfinished = true; 
Currently all threads download Total Downloadedallsize = 0; 
for (int i = 0; i < threads.length i++) {downloadedallsize + = Threads[i].getdownloadlength (); 
if (!threads[i].iscompleted ()) {isfinished = false; }//Notify HanDler to update the view component message msg = new Message (); 
Msg.getdata (). Putint ("size", downloadedallsize); 
Mhandler.sendmessage (msg); 
LOG.D (TAG, "current downloadsize:" + downloadedallsize); 
Thread.Sleep (1000);//rest 1 seconds before reading download progress} LOG.D (TAG, "All of Downloadsize:" + downloadedallsize); 
catch (Malformedurlexception e) {e.printstacktrace (); 
catch (IOException e) {e.printstacktrace (); 
catch (Interruptedexception e) {e.printstacktrace (); } 
} 
} 
}

Filedownloadthread:

Package Com.amos.app; 
Import Java.io.BufferedInputStream; 
Import Java.io.File; 
Import java.io.IOException; 
Import Java.io.RandomAccessFile; 
Import Java.net.URL; 
Import java.net.URLConnection; 
Import Android.util.Log;  /** * File Download class * * @author Yangxiaolong * @2014-5-6/public class Filedownloadthread extends Thread {private static 
Final String TAG = FileDownloadThread.class.getSimpleName (); 
/** whether the current download is complete */private Boolean iscompleted = false; 
/** Current Download File length * * Private int downloadlength = 0; 
/** files save path/private file file; 
/** File Download Path * * Private URL DownloadURL; 
/** current Download Thread ID */private int threadId; 
/** thread Download Data length * * private int blockSize; /** * * @param url: File Download address * @param file: Save path * @param blocksize: Download Data length * @param threadId: Thread ID/Public FILEDOWNL 
Oadthread (URL downloadurl, file file, int blocksize, int threadId) {this.downloadurl = DownloadURL; 
This.file = file; 
This.threadid = threadId; 
This.blocksize = blockSize; } @Override public voidRun () {Bufferedinputstream bis = null; 
Randomaccessfile RAF = null; 
try {URLConnection conn = downloadurl.openconnection (); 
Conn.setallowuserinteraction (TRUE); int startpos = BlockSize * (threadId-1)//start position int endpos = blockSize * threadid-1;//End position//Set start point for current thread download, endpoint Conn.set 
Requestproperty ("Range", "bytes=" + startpos + "-" + endpos); 
System.out.println (Thread.CurrentThread (). GetName () + "bytes=" + startpos + "-" + endpos); 
byte[] buffer = new byte[1024]; 
bis = new Bufferedinputstream (Conn.getinputstream ()); 
RAF = new Randomaccessfile (file, "RWD"); 
Raf.seek (startpos); 
int Len; 
while (len = bis.read (buffer, 0, 1024))!=-1) {raf.write (buffer, 0, Len); 
Downloadlength = Len; 
} iscompleted = true; 
LOG.D (TAG, "Current thread task has Finished,all size:" + downloadlength); 
catch (IOException e) {e.printstacktrace (); 
finally {if (bis!= null) {try {bis.close (); 
catch (IOException e) {e.printstacktrace (); } if (RAF!= null) {try {RAF. Close (); 
catch (IOException e) {e.printstacktrace (); 
}}/** * thread file is downloaded/public boolean iscompleted () {return iscompleted; 
/** * Thread Download file length */public int getdownloadlength () {return downloadlength; } 
}

Effect Chart:


Log console:

You can see the total size of the file, the 5 threads we created, each interval responsible for downloading

SD card:

About Android to achieve network multithreading file download small series to introduce so many people, I hope to help you! At the same time, thank you very much for your support of cloud-dwelling community!

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.