Code is very simple and practical, here is no more nonsense, directly to the source code
Package android.mooc.tools;
Import Java.io.BufferedInputStream;
Import Java.io.File;
Import Java.io.RandomAccessFile;
Import Java.net.URL;
Import java.net.URLConnection;
Import Android.util.Log;
public class Filedownloadthread extends Thread {private static final int buffer_size = 1024;
Private URL URL;
private file file;
private int startposition;
private int endposition;
private int curposition;
Used to identify whether the current thread is downloading complete private Boolean finished = false;
private int downloadsize;
Private Boolean state;
Boolean destory;
public Boolean isdestory () {return destory;
} public void Setdestory (Boolean destory) {this.destory = Destory;
Public filedownloadthread (URL url, file file, int startposition, int endposition) {this.url = URL;
This.file = file;
This.startposition = startposition;
This.curposition = startposition;
This.endposition = endposition;
this.downloadsize = 0;
@Override public void Run () { Destory = false;
state = true;
Bufferedinputstream bis = null;
Randomaccessfile fos = null;
byte[] buf = new Byte[buffer_size];
URLConnection con = null;
try {con = url.openconnection ();
Con.setallowuserinteraction (TRUE);
Set the starting point for the current thread download, end Con.setrequestproperty ("Range", "bytes=" + startposition + "-" + endposition);
Con.setrequestproperty ("Accept", "*/*");
Con.setrequestproperty ("Connection", "keep-alive");
Con.setrequestproperty ("Accept-language", "ZH-CN");
Con.setrequestproperty ("Charset", "UTF-8"); Con.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 8.0; Windows NT 5.2;
trident/4.0. NET CLR 1.1.4322; "
+ ". NET CLR 2.0.50727;. NET CLR 3.0.04506.30;. NET CLR 3.0.4506.2152;. NET CLR 3.5.30729)");
Random Read and write to files using Randomaccessfile in Java fos = new Randomaccessfile (file, rw);
Sets the location at which to start writing files Fos.seek (startposition); bis = new BUFFEREDINPUtstream (Con.getinputstream ());
Start the loop to read and write files as a stream while (Curposition < endposition) && (!destory)) {while (state = = False) {
Sleep (2000);
int len = bis.read (buf, 0, buffer_size);
if (Len!=-1) {fos.write (buf, 0, Len);
Curposition = curposition + len;
if (Curposition > endposition) {downloadsize = Len-(curposition-endposition);
else {downloadsize = Len;
} log.i ("333", "Run" + "len=" + len);
///Download complete set to True this.finished = true;
Bis.close ();
Fos.close ();
catch (Exception e) {e.printstacktrace ();
} public boolean isstate () {return state;
public void SetState (Boolean state) {this.state = state;
public Boolean isfinished () {return finished;
public int getdownloadsize () {return downloadsize; } public void Setdownloadsize (int downloadsize) {this.downloadsize = downloadsize;
}
}
The above is the entire contents of this article, I hope you can enjoy.