Android implementation of multithreading breakpoint download method

Source: Internet
Author: User
Tags file size range tostring

This article describes the Android implementation of multithreaded breakpoint download method. Share to everyone for your reference. The implementation methods are as follows:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148-149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179-18 0 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209-210 211 212 213 214 215 216 217 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 B T Private TextView TV; Private EditText et; Boolean flag = true; Boolean stopflag = false; Private Handler Handler = new HandlER () {@Override public void handlemessage (. msg) {pb.setprogress (total); int max = Pb.getmax (); if (Total >= (m Ax-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 periodically update the UI if ("Start downloading". Equals (Bt.gettex T (). 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 {1000);//If total > = file Length message msg = new Me Ssage (); Handler. SendMessage (msg); catch (Interruptedexception e) {e.printstacktrace ();}} }}.start ();  //Start 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 ~ End of File * * 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 (); Class Downloadtask extends Thread {int threadid; String filepath; int startposition; int Endpositon; Public downloadtask (int threadid, String filepath, int startposition, int endpositon) {this.threadid = ThreadID; this.fil Epath = 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 (f Is); String str = new string (result); if (! "". Equals (str)) {int newstartposition = Integer.parseint (str); if (Newstartposition > startposition) {startposition = NE Wstartposition; }}//"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); s Ynchronized (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.len Gth ()); } }

I hope this article will help you with your Android program.

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.