Android----Breakpoints Multi-threaded download

Source: Internet
Author: User

In tomcat6.0 webapps\root an. exe executable file (if you put. mp3,. jpg, and so on, the download process can be corrupted or viewable, If the. exe executable file download process is corrupted, then start Tomcat, double-click the Startup.bat under the Bin folder, and the following interface appears

Remember not to close this form, if you close the subsequent file download will be wrong.

The Android layout file code is as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "Vertical" tools:context= ". Mainactivity "> <edittext android:id=" @+id/et_path "android:layout_width=" Fill_parent "Andro id:layout_height= "Wrap_content" android:singleline= "true" android:text= "Http://172.29.168.1:8088/fengxing.ex E "/> <progressbar android:id=" @+id/pb "style="? Android:attr/progressbarstylehorizontal "and    Roid:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:layout_margintop= "28DP"/>        <button android:id= "@+id/bt" android:onclick= "Download" android:layout_width= "Wrap_content"    android:layout_height= "Wrap_content" android:layout_gravity= "center_horizontal" android:text= "Download"/> <textView android:id= "@+id/tv_show" android:layout_width= "wrap_content" android:layout_height= "Wrap_conten T "android:text=" The current download progress: "/></linearlayout>

effects such as:

For convenience, the download path was written dead in the code.

The code in Mainactivity is as follows:

Package Com.myself.download;import Java.io.file;import Java.io.fileinputstream;import java.io.InputStream;import Java.io.randomaccessfile;import Java.net.httpurlconnection;import Java.net.url;import Android.os.Bundle;import Android.os.environment;import Android.os.handler;import Android.os.message;import Android.app.Activity;import Android.text.textutils;import Android.view.menu;import Android.view.view;import Android.widget.Button;import Android.widget.edittext;import Android.widget.progressbar;import Android.widget.textview;import  Android.widget.toast;public class Mainactivity extends Activity {protected static final int down_load_error = 1;protected static final int server_error = 2;protected static final int sd_unable = 3;public static final int down_load_finish = 4;p    ublic static final int update_text = 5;public static int threadcount = 3;        public static int runingthread = 3; public int currentprocess=0;//Current Progress private EditText et_path;private ProgressBar pb;private TextView tv_show;private Handler handler=new Handler () {public void Handlemessage (Android.os.Message msg) {SW Itch (msg.what) {case DOWN_LOAD_ERROR:Toast.makeText (mainactivity.this, "Download Error", 1). Show (); Break;case Server_error: Toast.maketext (mainactivity.this, "Server connection Error", 1). Show (); Break;case SD_UNABLE:Toast.makeText (Mainactivity.this, " SD card Not available ", 1). Show (); Break;case DOWN_LOAD_FINISH:Toast.makeText (Mainactivity.this," Resource downloaded ", 1). Show (); break;case         UPDATE_TEXT:tv_show.setText ("Current Download Progress:" +pb.getprogress () *100/pb.getmax () + "%"); break;default:break;} };}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main) et_path= (EditText) Findviewbyid (R.id.et_path);p b= (ProgressBar) Findviewbyid (R.ID.PB); tv_ show= (TextView) Findviewbyid (r.id.tv_show);} public void Download (View v) {final String path=et_path.gettext (). toString (). Trim (); if (Textutils.isempty (path)) { Toast.maketext (This, "Download path cannot be empty", 1). Show (); return;}New Thread () {public void run () {//1. Connect to the server, get the length of the file to download, and create a temporary file that is the same size as the resource you want to download try {//string path = "http:// 172.29.168.1:8088/fengxing.exe "; URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"); int code = Conn.getresponsecode (); System.out.println ("code:" +code); if (code = = 200) {//The length of the data returned by the server is actually the length of the file int length = Conn.getcontentlength ();p B.set Max (length);//system.out.println ("Total file length:" + length);//Determine if the SD card is available if (Environment.getexternalstoragestate (). Equals ( environment.media_mounted)) {//Create a temporary file on the client that is the same size as the resource to be downloaded Randomaccessfile raf=new randomaccessfile ("/sdcard/ Fengxing.exe "," RWD ");//sets the size of the file raf.setlength (length); Raf.close ();//Assuming that 3 threads are going to download//average size of the resources downloaded per thread int blockSize = length/threadcount;for (int threadId = 1; threadId <= threadcount; threadid++) {//Where the first thread begins to download int startIndex = (thre ADID-1) * Blocksize;int EndIndex = (threadId * blockSize)-1;if (threadId = threadcount) {//The last thread downloaded is the remainingThe resource endindex = length;} SYSTEM.OUT.PRINTLN ("Thread" +threadid+ "Thread download location:" +startindex+ "------->" +endindex "); new Downlload (ThreadId, StartIndex, EndIndex, Path). Start ();}} ELSE{SYSTEM.OUT.PRINTLN ("SD card not available ..."); Message msg=new message (); Msg.what=sd_unable;handler.sendmessage (msg);}} else {System.out.println ("Server connection Error ..."); Message msg=new message (); Msg.what=server_error;handler.sendmessage (msg);}} catch (Exception e) {e.printstacktrace (); Message msg=new message (); Msg.what=down_load_error;handler.sendmessage (msg);}};}. Start ();} /** * Download file sub-thread each thread downloads the file corresponding to the location * @author Administrator * */public class Downlload extends thread{private int Threadid;pri vate int startindex;private int endindex;private String path;/** * * @param threadId thread ID * @param startIndex where to start download *  @param endIndex End Position * @param path of the resource to download */public downlload (int threadId, int startIndex, int endIndex, String path) {This.threadid = Threadid;this.startindex = Startindex;this.endindex = Endindex;this.path = path;} @Overridepublic void run () {try {//checks for the existence of a file that has been downloaded for the length of the file and, if present, reads the contents of the files ("/sdcard/" +threadid+ ". txt") tempfile=new Tempfile.exists () &&tempfile.length () >0) {FileInputStream fis=new fileinputstream (tempFile); byte[] Temp= New Byte[1024];int Leng=fis.read (temp); String Downloadlen=new string (temp,0,leng); int downloadint=integer.parseint (downloadlen); int alreadydownint= DOWNLOADINT-STARTINDEX;//has already downloaded the progress currentprocess+=alreadydownint;//if already has the download, the Reset Progress startindex=downloadint;// Modify the download real start location}url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET");//Important: The file that requests the server Download section specifies the downloaded resource range Conn.setrequestproperty ("range", "bytes=" +startindex+ "-" +endindex); SYSTEM.OUT.PRINTLN ("Thread" +threadid+ "thread restarts the download location:" +startindex+ "------->" +endindex); int code = Conn.getresponsecode ();//200 represents the total resource 206 for a portion of the resource//system.out.println ("code:" +code); if (code==206) {InputStream is =conn.getinputstream ()///has set the requested location to return the input stream of the file corresponding to the current location RANDOMACCESSFILe raf=new randomaccessfile ("/sdcard/fengxing.exe", "RWD") Raf.seek (StartIndex);//positioning start position int len=0;byte[] Buff=new Byte[1024];int total=0;//records the length of the file that has been downloaded while ((Len=is.read (Buff))!=-1) {//fileoutputstream fos=new FileOutputStream ( file); Randomaccessfile file=new randomaccessfile ("/sdcard/" +threadid+ ". txt", "RWD");//Record the length of the current thread download raf.write (buff, 0, Len); TOTAL+=LEN;//SYSTEM.OUT.PRINTLN ("Thread" +threadid+ "Download Length:" +total); File.write (("" + (Total+startindex)). GetBytes ()); File.close ();//Update progress bar synchronized (mainactivity.this) {currentprocess+=len;//Get the total progress of all thread downloads pb.setprogress ( currentprocess);//Change progress bar Progress message msg=message.obtain ();//Reuse Old message msg.what=update_text;handler.sendmessage (msg);}} Is.close (); Raf.close (); SYSTEM.OUT.PRINTLN ("Thread" +threadid+ "Download Complete ..."); ELSE{SYSTEM.OUT.PRINTLN ("Thread" +threadid+ "Download failed ..."); /*file deletefile=new File (threadid+ ". txt");d eletefile.delete (); */} catch (Exception e) {e.printstacktrace ();} Finally{threadfinish ();}} Private synchronized void Threadfinish () {//function of this part: Prevents a record file from being deleted after the resource has been downloaded runIngthread--;if (runingthread==0) {for (int i=1;i<=3;i++) {file File=new file ("/sdcard/" +i+ ". txt"); File.delete ();} SYSTEM.OUT.PRINTLN ("The resource has been downloaded, delete all download records ..."); Message msg=new message (); Msg.what=down_load_finish;handler.sendmessage (msg);}}}

run by:

In the process of downloading, exiting the program, and then opening the program, the program will continue to download on the original basis.

When you finally open SDcard in file Explor, you will find the downloaded file:



Source code: http://download.csdn.net/detail/dangnianmingyue_gg/9026189




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android----Breakpoints Multi-threaded download

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.