Androsh Training Seventh Day---Multi-threaded download implementation (progress bar)

Source: Internet
Author: User

Packagecom.example.download;import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.inputstream;import Java.io.randomaccessfile;import Java.net.httpurlconnection;import Java.net.url;import Android.app.activity;import Android.os.Bundle;import Android.os.environment;import Android.os.handler;import Android.text.textutils;import Android.view.View;import Android.widget.edittext;import Android.widget.progressbar;import Android.widget.textview;import Android.widget.toast;public class Mainactivity extends Activity {//define executing thread private int threadrunning = 3;//thread Open number Priv ate int threadnum = 3;private EditText et_url;//progress bar Private ProgressBar progressbar;private TextView tv_pb;private int cur  Rentprogress = 0;private Boolean flag = true;//Record the value of the progress bar public static int pb_count = 0;public static Handler handler;public static final int textvalue = 1;public static int pb_num = 0;public static int size = 0; @Overrideprotected void OnCreate (B Undle SavedinstanCestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);//Get Control object Et_url = (EditText) Findviewbyid (r.id.et_url);p Rogressbar = (progressBar) Findviewbyid (r.id.tv_jindu); TV_PB = (TextView) Findviewbyid ( R.ID.TV_PB); File Sddir = Environment.getexternalstoragedirectory (); File Pdfile = new file (Sddir, "pb.txt"); InputStream is = null;try {if (pdfile.exists ()) {is = new FileInputStream (pdfile); }} catch (FileNotFoundException e) {e.printstacktrace ();} if (is! = null) {String value = Streamtools.streamtostr (IS); String arr[] = Value.split (";"); Progressbar.setmax (Integer.valueof (arr[0]));//Max currentprogress = integer.valueof (arr[1]);// Current value progressbar.setprogress (currentprogress);; Tv_pb.settext ("Current progress is" + arr[2] + "%");}} public void DownLoadFile (View v) {//interview address: final String spec = Et_url.gettext (). toString ();//"http://172.16.237.144:8080 /login/football.jpg ", if (Textutils.isempty (spec)) {Toast.maketext (this," cannot be empty ", Toast.length_long). Show ();} else { New Thread () {public void run () {try {URL url = new URL (spec); HttpURLConnection httpurlconnection = (httpurlconnection) url.openconnection ();// Set the requested header file information there is time Httpurlconnection.setrequestmethod ("GET"); Httpurlconnection.setconnecttimeout (5000); Httpurlconnection.setreadtimeout, if (httpurlconnection.getresponsecode () = =) {int filelength = Httpurlconnection.getcontentlength ()///Set the maximum value of the progress bar Progressbar.setmax (filelength);//infer if your device sdcard is available if ( Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {//External storage device path File Sdfile = Environment.getexternalstoragedirectory ();//Gets the name of the file string fileName = Spec.substring (Spec.lastindexof ("/") + 1);// Create the saved files file = new file (Sdfile, fileName);//create random Access Files Object Randomaccessfile accessfile = new Randomaccessfile (file, "R WD ");//Set File size Accessfile.setlength (filelength);//close Operation Accessfile.close ();//First calculate the size of each thread download start position int threadsize = filelength/threadnum;//for Loop open threading for (int threadId = 1; threadId <= 3; threadid++) {int startIndex = (ThreadiD-1) * threadsize;//start position int endIndex = threadId * THREADSIZE-1;IF (threadId = = threadnum) {//last thread EndIndex = FileLen Gth-1;} System.out.println ("Current thread--" + threadid+ "start position---" + startindex+ "End Position---" + endIndex + "thread size---");//start thread download to use the Start method new do Wnloadthread (ThreadId, Startindex,endindex, Spec, fileName). Start ();}} else {MainActivity.this.runOnUiThread (new Runnable () {@Overridepublic void run () {Toast.maketext (Mainactivity.this, " The device's SD card is not available ", Toast.length_long). Show ();}});}} else {//This allows it to execute MainActivity.this.runOnUiThread in the main thread (new Runnable () {@Overridepublic void run () {Toast.maketext ( Mainactivity.this, "Server side returned error", Toast.length_long). Show ();}});}} catch (Exception e) {e.printstacktrace ();}};}. Start ();}} Class Downloadthread extends Thread {private int threadid;private int startindex;private int endindex;private String path; Private String filename;public downloadthread (int threadId, int startIndex, int endindex,string path, String fileName) {su Per (); This.threadid = threadid;thIs.startindex = Startindex;this.endindex = Endindex;this.path = Path;this.filename = FileName;} @Overridepublic void Run () {//is capable of downloading files through each thread. try {file Sdfile = Environment.getexternalstoragedirectory ();//get each thread to download the record file Recordfile = new file (Sdfile, ThreadId + ". txt");//Infer if the record file exists if (recordfile.exists ()) {//Read the contents of the file InputStream is = new FileInputStream (recordfile);//Lee Use the tool class to convert string value = Streamtools.streamtostr (IS);//get record position int recordindex = Integer.parseint (value);// The recorded location is copied to the beginning of the location can be startindex = Recordindex;} Build URL object URL url via path path = new URL (path);//Return object HttpURLConnection httpurlconnection = (httpurlconnection) via open connection to URL object Url.openconnection ();//Set Request header Httpurlconnection.setrequestmethod ("GET"); Httpurlconnection.setconnecttimeout (5000 )///Set the start and end location of the download file Httpurlconnection.setrequestproperty ("Range", "bytes=" + StartIndex + "-" + endIndex);//Gets the state of int Code = Httpurlconnection.getresponsecode (); if (code = = 206) {//Gets the stream object returned by each thread: inputstream InputStream = Httpurlconnection.getinpuTStream ();//Gets the file name because it passed over there//String filename =//path.substring (path.lastindexof ("/") +1);//external storage device path File File = New file (Sdfile, fileName);//Create her Randomaccessfile object according to the file Randomaccessfile RAF = new Randomaccessfile (file, "RWD"); Raf.seek (StartIndex);//define the length of the read int len = 0;byte buffer[] = new Byte[50];int total = 0;//loop read while (len = Inputstream.rea d (buffer))! =-1) {System.out.println ("Current thread--" + ThreadId + "--Already downloaded" + (StartIndex + total));//Create a thread to download the recorded file Randomaccessfi Le threadfile = new Randomaccessfile (new File (sdfile, ThreadId + ". txt"), "RWD"); Threadfile.writebytes ((StartIndex + Tota L) + ""); Threadfile.close (); raf.write (buffer, 0, Len), Total + = len;synchronized (mainactivity.this) {currentprogress + = Len;progressbar.setprogress (currentprogress);//Calculate percent operation intfinal String percent = currentprogress * 100l/ Progressbar.getmax () + ""; MainActivity.this.runOnUiThread (New Runnable () {@Overridepublic void run () {Tv_pb.settext ("Current progress is:" + percent + "%");}); Randomaccessfile pbfile = new RaNdomaccessfile (New File (Sdfile, "Pb.txt"), "RWD");p Bfile.writebytes (Progressbar.getmax () + ";" + currentprogress + ";" + percent);p bfile.close ();}} Raf.close (); Inputstream.close (); MainActivity.this.runOnUiThread (New Runnable () {@Overridepublic void Run () {///SYSTEM.OUT.PRINTLN ("Current thread----" + threadid+ "complete Download"); Toast.maketext (mainactivity.this, "current thread----" + threadId + "complete download", Toast.length_long). Show ();}); Deleterecordfiles ();} else {MainActivity.this.runOnUiThread (new Runnable () {@Overridepublic void run () {Toast.maketext (Mainactivity.this, " Server-Side Download Error ", Toast.length_long). Show ();}});}} catch (Exception e) {e.printstacktrace ();}}} Public synchronized void Deleterecordfiles () {File sdfile = Environment.getexternalstoragedirectory (); System.out.println ("-------------------------"); Threadrunning--;if (threadrunning = = 0) {for (int i = 1; I <= 3; i++) { File Recordfile = new file (sdfile, i + ". txt"), if (Recordfile.exists ()) {Boolean Flag1 = Recordfile.delete ();//delete Files Syste M.out.println ("Download record" + i +"File has" + Flag1 + "delete");} File Pdfile = new file (sdfile, "Pb.txt"), if (Pdfile.exists ()) {Boolean flag2 = Pdfile.delete (); System.out.println ("Progress bar record file has" + flag2 + "delete");}}} public void Displaymsg () {}}


Bug Considerations:

1. Continue the thread download file must be running Threadfile.close (), otherwise you will not be able to run the subsequent deletion of the TXT file section.

2, must pay attention to the download speed settings, not too fast. exceeds the size of the transfer file. Otherwise it will cause the simulator to die.

Androsh Training Seventh Day---Multi-threaded download implementation (progress bar)

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.