Android multi-thread download

Source: Internet
Author: User

Declare in advance that the main class files used by this program are the knowledge in crazy android handouts.

I just tried it by downloading an LRC lyrics file.

The layout file is as follows:

<Relativelayout 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"> <button Android: id = "@ + ID/button1" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_alignparentleft = "true" Android: TEXT = "Download"/> <progressbar Android: Id = "@ + ID/progress Bar1 "style = "? Android: ATTR/progressbarstylehorizontal "Android: layout_width =" fill_parent "Android: layout_height =" wrap_content "Android: Rule =" true "Android: layout_alignparentright =" true "Android: layout_below = "@ + ID/button1"/> </relativelayout>

Main activity files

Package COM. example. downloadthread; import Java. io. file; import Java. io. ioexception; import Java. util. timer; import Java. util. timertask; 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. progressbar; public class mainactivity2 extends activity {private progressbar; private button; private string filepath = "/mnt/sdcard/AAA. LRC "; private string url =" http://box.zhangmen.baidu.com/bdlrc/9064/906474.lrc "; private int threadnum = 4; private downutil; private int mdownstatus; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); button = (button) findviewbyid (R. id. button1); progressbar = (progressbar) findviewbyid (R. id. progressbar1); button. setonclicklistener (New onclicklistener () {public void onclick (view v) {file = new file (URL); If (file. exists () = false) {try {file. createnewfile ();} catch (ioexception e) {e. printstacktrace () ;}} download () ;}}) ;}final handler = new handler () {@ overridepublic void handlemessage (Message MSG) {If (MSG. what = 0x123) {progressbar. setprogress (mdownstatus) ;}}; private void download () {downutil = new downutil (threadnum, URL, filepath); try {downutil. download ();} catch (exception e) {e. printstacktrace ();} final timer = new timer (); timer. schedule (New timertask () {@ overridepublic void run () {// obtain the download task completion rate double completerate = downutil. getcompleterate (); mdownstatus = (INT) (completerate * 100); // update the progress bar handler on the Send Message notification page. sendemptymessage (0x123); // After the download is complete, cancel the task scheduling if (mdownstatus> = 100) {timer. cancel () ;}}, 0,100 );}}

Download help files

Package COM. example. downloadthread; import Java. io. inputstream; import Java. io. randomaccessfile; import java.net. httpurlconnection; import java.net. URL; public class downutil {private int threadnum; private string strurl; private string filepath; private downloadthread threads []; // defines the total size of the downloaded file private int filesize; /*** @ Param threadnum * thread count * @ Param URL * download URL * @ Param filepath * file storage path **/Public down Util (INT threadnum, string URL, string filepath) {super (); this. threadnum = threadnum; this. strurl = URL; this. filepath = filepath; this. threads = new downloadthread [threadnum];} void download () throws exception {URL url = new URL (strurl); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (5*1000); Conn. setrequestmethod ("get"); Conn. setrequestproperty ("accept", "imag E/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 ("User-Agent "," Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0 ;. net CLR 1.1.4322 ;. net CLR 2.0.50727 ;. net CLR 3.0.04506.30 ;. net CLR 3.0.20.6.2152 ;. net CLR 3.5.30729) "); Conn. setrequestproperty ("connection", "keep-alive"); // obtain the file size filesize = Conn. getcontentlength (); Conn. disconnect (); int currentpartsize = filesize/threadnum + 1; randomaccessfile file = new randomaccessfile (filepath, "RW"); // set this Local file size file. setlength (filesize); file. close (); For (INT I = 0; I <threadnum; I ++) {// calculate the start position of download for each thread, int startpos = I * currentpartsize; // each thread uses a randomaccessfile to download randomaccessfile currentpart = new randomaccessfile (filepath, "RW"); // locate the download location of the thread currentpart. seek (startpos); // create the download thread threads [I] = new downloadthread (startpos, currentpartsize, currentpart); // start the download thread threads [I]. start () ;}} class downloadthre Ad extends thread {// The download location of the current thread private int startpos; // defines the file size private int currentpartsize that the current thread is responsible for downloading; // The file block private randomaccessfile currentpart to be downloaded by the current thread; // defines the number of bytes that have been downloaded by this thread. Public downloadthread (INT startpos, int currentpartsize, randomaccessfile currentpart) {This. startpos = startpos; this. currentpartsize = currentpartsize; this. currentpart = currentpart;} @ overridepublic void run () {try {URL url = new URL (strurl); 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 (); // skip the startpos byte, indicating that the thread only downloads the part of the file that it is responsible. Instream. skip (this. startpos); byte [] buffer = new byte [1024]; int hasread = 0; // reads network data, and write the while (length <currentpartsize & (hasread = instream. read (buffer ))! =-1) {currentpart. write (buffer, 0, hasread); // The total download size of this thread. Length + = hasread;} currentpart. close (); instream. close ();} catch (exception e) {e. printstacktrace () ;}}// get the download completion percentage public double getcompleterate () {// count the total size of multiple threads that have been downloaded int sumsize = 0; for (INT I = 0; I <threadnum; I ++) {sumsize + = threads [I]. length ;}/// return the percentage of completed results returned. Return sumsize * 1.0/filesize;} public int getthreadnum () {return threadnum;} public void setthreadnum (INT threadnum) {This. threadnum = threadnum;} Public String geturl () {return strurl;} public void seturl (string URL) {This. strurl = URL;} Public String getfilepath () {return filepath;} public void setfilepath (string filepath) {This. filepath = filepath ;}}

Because the sdcard support is required, I have to attach all permissions.

    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    <uses-permission android:name="android.permission.READ_PHONE_STATE" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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.