This article illustrates the way Android implements multithreaded breakpoint downloads. Share to everyone for your reference. The implementation method is as follows:
Package cn.itcast.download;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.RandomAccessFile;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import java.net.ProtocolException;
Import Java.net.URL;
Import Cn.itcast.mutiledownload.StreamTool;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.ProgressBar;
Import Android.widget.TextView;
Import Android.widget.Toast;
public class Mutiledownloadactivity extends activity implements Onclicklistener {private ProgressBar PB;
Private Button BT;
Private TextView TV;
Private EditText et;
Boolean flag = true; Boolean Stopflag =False Private Handler Handler = new Handler () {@Override public void Handlemessage (msg) {Pb.setprogre
SS (total);
int max = Pb.getmax ();
if (total >= (max-1)) {total = max;
Flag = false;
int result = Total * 100/MAX;
Tv.settext ("Current progress:" + result + "%");
Super.handlemessage (msg);
}
};
int total = 0;
@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
PB = (ProgressBar) This.findviewbyid (R.ID.PB);
BT = (Button) This.findviewbyid (R.ID.BT);
TV = (TextView) This.findviewbyid (r.id.tv_process);
ET = (edittext) This.findviewbyid (r.id.et);
Bt.setonclicklistener (this);
@Override public void OnClick (View v) {switch (V.getid ()) {case R.ID.BT://Create a child thread to update the UI periodically
if ("Start Download". Equals (Bt.gettext (). toString ())) {Bt.settext ("paused"); Stopflag = false;
Start Download} else {bt.settext ("start download");
Stopflag = true;
New Thread () {@Override public void run () {super.run ();
while (flag) {try {sleep (1000);
If total > = file length msg = new Message ();
Handler.sendmessage (msg);
catch (Interruptedexception e) {e.printstacktrace ();
}}}.start ();
Start the download operation String path = Et.gettext (). toString (). Trim ();
if ("". Equals (Path)) {Toast.maketext (this, "path cannot be empty", 1). Show ();
Return
try {URL url = new URL (path);
HttpURLConnection conn = (httpurlconnection) URL. OpenConnection ();
Conn.setrequestmethod ("get");
Conn.setconnecttimeout (5000); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 6.0; Windows NT 5.1;
SV1) ");
int code = Conn.getresponsecode ();
if (code = =) {int len = conn.getcontentlength ();
Randomaccessfile file = new Randomaccessfile ("/mnt/sdcard/" + getfilenname (Path), "RWD");
1. Set the local file size consistent with the file size of the server file.setlength (len);
Sets the maximum value of the progress bar Pb.setmax (LEN);
2. Suppose to open 3 threads int threadnumber = 3;
int blocksize = Len/threadnumber; /** * Thread 1 0~ blocksize thread 2 1*bolocksize ~ 2*blocksize Thread 3 * 2*blocksize ~ File End *
/for (int i = 0; i < threadnumber; i++) {int startposition = i * blocksize;
int Endpositon = (i + 1) * BLOCKSIZE; if (i = = (threadnumber-1)) {//Last thread EndposIton = Len;
} downloadtask task = new Downloadtask (i, Path, startposition, Endpositon);
Task.start ();
(Exception e) {Toast.maketext (this, "Exception on Download", 0). Show ();
E.printstacktrace ();
} break;
Class Downloadtask extends Thread {int threadid;
String filepath;
int startposition;
int Endpositon; Public downloadtask (int threadid, String filepath, int startposition, int endpositon) {this.threadid = th
Readid;
This.filepath = filepath;
This.startposition = startposition;
This.endpositon = Endpositon; @Override public void Run () {try {file Postionfile = new file ("/mnt/sdcard/" + ThreadID +).
TXT ");
URL url = new URL (filepath);
HttpURLConnection conn = (httpurlconnection) URL. OpenConnection (); System.OUT.PRINTLN ("thread" + ThreadID + "is downloading" + "start position:" + startposition + "End position" + Endpositon);
if (postionfile.exists ()) {FileInputStream FIS = new FileInputStream (postionfile);
Byte[] result = Streamtool.getbytes (FIS);
String str = new string (result); if (! "".
Equals (str)) {int newstartposition = Integer.parseint (str);
if (Newstartposition > startposition) {startposition = newstartposition; }}//' range ', ' bytes=2097152-4194303 ' conn.setrequestproperty (' range ', ' bytes= '
+ startposition + "-" + Endpositon);
Conn.setrequestmethod ("get");
Conn.setconnecttimeout (5000); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 6.0; Windows NT 5.1;
SV1) ");
InputStream is = Conn.getinputstream (); Randomaccessfile file = new Randomaccessfile ("/MNT/SDCArd/"+ getfilenname (filepath)," RWD ");
Sets the data from which location of the file to write File.seek (startposition);
byte[] buffer = new byte[1024];
int len = 0;
Represents the location of the server data currently being read, while this value has been stored in the location of the file int currentpostion = startposition; Creates a file object that records the download location of the current file while (len = is.read (buffer)!=-1) {if (Stopflag) {return
;
} file.write (buffer, 0, Len);
Synchronized (mutiledownloadactivity.this) {total = Len;
} currentpostion = Len;
The currentpostion information needs to be persisted to the storage device String position = currentpostion + "";
FileOutputStream fos = new FileOutputStream (postionfile);
Fos.write (Position.getbytes ());
Fos.flush ();
Fos.close ();
} file.close ();
SYSTEM.OUT.PRINTLN ("thread" + threadid + "Download Complete");
Delete the file after the thread has been downloaded if (postionfile.exists ()) { Postionfile.delete ();
} catch (Exception e) {e.printstacktrace ();
} super.run ();
} public string Getfilenname (string path) {int start = Path.lastindexof ("/") + 1;
Return path.substring (Start, path.length ()); }
}
I hope this article will help you with your Android program.