Android rookie road-multi-threaded download

Source: Internet
Author: User
Tags response code

Android Client Download steps
    1. The Android client first creates an empty file (blank file) that is exactly the same size as the server.
    2. Open several threads to download the corresponding resources on the server respectively.
    3. If all the threads are downloaded, the server's resources are downloaded.
Android Client Download logic
  1. Gets the size of the server-side resource file (connection.getcontentlength ())

    String path = "http://localhost:8080/ff.exe";URL url = new URL(path);// 获取链接HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 参数connection.setRequestMethod("GET");connection.setConnectTimeout(5000);// 响应码int responseCode = connection.getResponseCode();if (responseCode == 200) {    // 得到服务端返回的文件大小    long contentLength = connection.getContentLength();    System.out.println("服务器文件大小:"+contentLength);}// 断开连接connection.disconnect();
  2. Create a local blank file of the same size and server

      File File = new file ("Temp.ext"); Randomaccessfile raf= New Randomaccessfile (file, "RW"); Raf.setlength (contentlength);  
  3. According to the number of open threads, the server resources are divided into several parts (threadcount: Number of threads)

    假设文件大小是10个byte。(长度:length)假设3个线程(线程数量:threadCount)。 int blockSize = length / threadCount;线程1 下载3个byte    1-3     0 * blockSize + 1 ~ 1 * blockSize线程2 下载3个byte    4-6     1 * blockSize + 1 ~ 2 * blockSize 线程3 下载4个byte    7-10    2 * blockSize + 1 ~ 3 * blockSize(length)// 开启若干个子线程,分别去下载对应的资源long threadCount = 3;long blockSize = contentLength / threadCount;for (int i = 1; i <= threadCount; i++) {    // 计算下载起始、结束位置    long startIndex = (i - 1) * blockSize + 0;// 服务器也是从0开始    long endIndex = i * blockSize - 1; //    // 最后一个线程    if (i == threadCount) {        endIndex = contentLength - 1;    }    System.out.println("开启线程:" + i + ",下载的位置:(" + startIndex + "~"            + endIndex + ")");    new DownloadThread(i, startIndex, endIndex, path).start();}
  4. Creating a Thread class

    Static Class Downloadthread extends Thread {private int threadId;    Private long StartIndex;    Private long EndIndex;    Private String path;        Public downloadthread (int threadId, long startIndex, long endIndex, String path) {super ();        This.threadid = threadId;        This.startindex = StartIndex;        This.endindex = EndIndex;    This.path = path;        } public void Run () {URL url;            try {url = new URL (path);            Gets the link httpurlconnection connection = (httpurlconnection) URL. OpenConnection ();            Parameter Connection.setrequestmethod ("GET");            Connection.setconnecttimeout (5000); Tell the server to download the parameter Connection.setrequestproperty ("Range", "bytes=" + StartIndex + "-" + EndIndex)            ;            Response code int responsecode = Connection.getresponsecode ();            SYSTEM.OUT.PRINTLN ("Server Status code:" + responsecode); Download service206 if (Responsecode = = 206) {InputStream InputStream = Connection.getinputstream ();                File File = new file ("Temp.exe");                Randomaccessfile RAF = new Randomaccessfile (file, "RW");                Specifies where the file begins to write Raf.seek (StartIndex);                System.out.println ("First" + ThreadId + "threads, write the start of the file, end position (" + (StartIndex) + "," + (EndIndex) + ")");                 int len = 0;                byte[] buf = new byte[1024];                while (len = Inputstream.read (BUF))! =-1) {raf.write (buf, 0, Len);                } inputstream.close ();                Raf.close ();            System.out.println ("First" + threadId + "Threads download Completed");        }} catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); }    }}

Android Rookie road-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.