Android------multi-threaded download

Source: Internet
Author: User

Using HttpURLConnection
HttpURLConnection inherits from URLConnection and can also be used to send a GET request to a specified Web site
POST request.

Method:

int Getresponsecode ():
Get the response code for the server

String getresponsemessage ():
Get the response message for the server

String Getresponsemethod ():
Get the method to send the request

void Setrequestmethod ():
To set the method for sending requests


Multi-Threaded Download
Steps:

1. Create a URL object
2. Gets the size of the resource pointed to by the specified URL object is implemented by Getcontentlength ()
3. Create an empty file on the local disk that is the same size as the network resource
4. Calculate the portion of the network resource that each thread should download (starting at which byte, to which end)
5. Create and start multiple threads sequentially to download the specified portion of the network resource.

Download Tool class:

Public class downutil{//defines the path to the download resource private string path;//specifies the location where the downloaded file is saved private string targetfile;// Defines how many threads need to be used to download the resource private int threadnum;//defines the downloaded thread object private downthread[] threads;//defines the total size of the downloaded file private int filesize;public Downutil (string path, string targetfile, int threadnum) {This.path = Path;this.threadnum = threadnum;// Initialize threads Array threads = new Downthread[threadnum];this.targetfile = TargetFile;} public void Download () throws Exception{url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5 * 1000); Conn.setrequestmethod ("GET"); Conn.setrequestproperty ("Accept", "Image/gif, Image/jpeg, Image/pjpeg, image/pjpeg," + "Application/x-shockwave-flash, Application/xaml+xml," + "application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP," + "Application/x-ms-application, Application/vnd.ms-excel," + "Application/vnd.ms-powerpoint, Application/msword, */* "); Conn.setrequestproperty (" Accept-language "," ZH-CN "); Conn.setrequestproperty (" Charset "," UTF-8 "); Conn.setrequestproperty (" Connection "," keep-alive ");//Get file size FileSize = Conn.getcontentlength (); Conn.disconnect (); int currentpartsize = Filesize/threadnum + 1; Randomaccessfile file = new Randomaccessfile (targetfile, "RW");//Set the size of local files file.setlength (fileSize); File.close (); for (int i = 0; i < threadnum; i++) {//Calculate the start of each thread's download int startpos = i * currentpartsize;//each thread uses a randomaccessfile to download randomaccessfile currentpart = new Ra Ndomaccessfile (TargetFile, "RW");//Locate the thread's download location Currentpart.seek (startpos);//create download thread threads[i] = new Downthread ( Startpos, Currentpartsize,currentpart);//Start Download thread Threads[i].start ();}} Gets the percent complete of the download public double getcompleterate () {//Statistics multiple threads have downloaded a total size of int sumsize = 0;for (int i = 0; i < threadnum; i++) {Sumsi Ze + = threads[i].length;} Returns the percentage that has been completed return sumsize * 1.0/filesize; Private class Downthread extends thread{//the current thread's download location private int startpos;//Defines the file size that the current thread is responsible for downloading private int currentpartsize;/ /When the front-thread needs to download the file Block private Randomaccessfile currentpart;//defines the number of bytes already downloaded by the thread public int length;public downthread (int startpos, int currentpartsize,randomaccessfile currentpart) {This.startPos = Startpos;this.currentpartsize = Currentpartsize;this.currentpart = Currentpart;} @Overridepublic void Run () {try{url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5 * 1000); Conn.setrequestmethod ("GET"); Conn.setrequestproperty ("Accept", "Image/gif, Image/jpeg, Image/pjpeg, image/pjpeg," + "Application/x-shockwave-flash, Application/xaml+xml," + "application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP," + "Application/x-ms-application, Application/vnd.ms-excel," + "Application/vnd.ms-powerpoint, Application/msword, */* "); Conn.setrequestproperty (" Accept-language "," ZH-CN "); Conn.setrequestproperty (" Charset "," UTF-8 "); InputStream Instream = Conn.getinputstream ();//skips startpos bytes, indicating that the thread only downloads which part of the file it is responsible for. Instream.skip (This.startpos); byte[] buffer = new Byte[1024];int Hasread = 0;//Reads network data and writes to local file while (length < CURRENTPA Rtsize&& (Hasread = instream.read (buffer)) > 0) {currentpart.write (buffer, 0, hasread);//Cumulative total size of the thread download length + = Hasread;} Currentpart.close (); Instream.close ();} catch (Exception e) {e.printstacktrace ();}}}}


Activity:

public class Mainactivity extends Activity {EditText URL; EditText Target; Button DownButton; ProgressBar bar;downutil downutil;private int mdownstatus; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); url = (EditText) Findviewbyid (R.id.url ); target = (EditText) Findviewbyid (r.id.target);d Ownbutton = (Button) Findviewbyid (r.id.down); bar = (ProgressBar) Findviewbyid (R.id.bar); final Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {if (MSG.WH at = = 0x123) {bar.setprogress (mdownstatus);}}; Downbutton.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {downutil = new Downutil ( Url.gettext (). ToString (), Target.gettext (). ToString (), 6); new Thread () {public void run () {try {downutil.download ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Final Timer timer = new timer (); Timer.schedule (new TimerTask () {@Overridepublic void ruN () {//Get completion ratio for download task Double completerate = Downutil.getcompleterate (); mdownstatus = (int) (completerate * 100);//Send Message Notification interface more New progress bar Handler.sendemptymessage (0x123);//download completely after canceling task scheduling if (Mdownstatus >=) {timer.cancel ();}}, 0, 100);};}. Start ();}});}}


Android------multi-threaded download

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.