Android Multi-Threading Download principle

Source: Internet
Author: User


In Android, for multi-threaded operation is very ordinary, so the more understanding of multithreading, then for their own program can be very good run

This is also an important point of knowledge for Android development, so let's now look at how multi-threaded download works.


Android Multi-Threaded download
Multi-Threaded Download step: 1. Create a local file temp file that is the same size as the server. 2. Calculate the location of each file download that allocates several threads to download resources on the server. 3. Turn on the thread, and each thread downloads the corresponding file. 4. If all the threads have downloaded their own data, the resources on the server will be downloaded locally.
: (assuming three threads are downloading)

Server side: 0 1 2 3 4 5 6 7 8 9
1. Length of File/3, gets the length of each thread download file. (assuming there are three threads to download) thread 1: Download 0-2 thread 2: Download 3-5 thread 3: Download 6-To the end of a file
Location of each file download start location: (thread id-1) * Every quick size end position: (thread ID) * Every quick size-1
Below, we first use Java code to implement the package com.zengtao.demo;


Import Java.io.InputStream;
Import Java.io.RandomAccessFile;
Import java.net.HttpURLConnection;
Import Java.net.URL;


public class Demoloader {
private static Demoloader loader = new Demoloader ();
private static int threadcount = 3;


Private Demoloader () {


}

Single Case design mode
public static Demoloader getinstance () {
return loader;
}


public void Downfile (String path) {
Go to the server side to get the length of the file, create a local file with the same size as the server
try {
URL url = new URL (path);
HttpURLConnection connection = (httpurlconnection) URL
. OpenConnection ();
Connection.setdoinput (TRUE);
Connection.setrequestmethod ("GET");
Connection.setreadtimeout (5000);
int code = Connection.getresponsecode ();
if (code = = 200) {
Gets the length of the server-side file
int filelength = Connection.getcontentlength ();
Create a local file of the same size as the server
Randomaccessfile RAF = new Randomaccessfile ("Setup.ext", "RWD");
Raf.setlength (filelength);
Raf.close ();
Suppose three threads are downloaded
int blockSize = Filelength/threadcount;
for (int threadId = 0; threadId < threadcount; threadid++) {
int startIndex = (threadId-1) * blockSize;
int endIndex = threadId * BLOCKSIZE-1;
if (threadId = = ThreadCount) {
EndIndex = Filelength;
}
System.out.println ("Thread:" + threadId + ", download:" + StartIndex
+ "--->" + endIndex);
Start download
New Downloadthread (ThreadId, StartIndex, EndIndex, Path)
. Start ();
}
SYSTEM.OUT.PRINTLN ("Total file length:" + filelength);
} else {
SYSTEM.OUT.PRINTLN ("Request failed! ");
}


} catch (Exception e) {
E.printstacktrace ();
}
}


/**
* Download the main thread of the file
*
* @author Administrator Zengtao
*
*/
public class Downloadthread extends Thread {
private int threadId;
private int startIndex;
private int endIndex;
Private String path;


/**
*
* @param threadId
* Thread ID
* @param startIndex
* Thread Download Start location
* @param endIndex
* Thread Download End location
* @param path
* Thread download end file drop address
*/
Public downloadthread (int threadId, int startIndex, int endIndex,
String path) {
Super ();
This.threadid = threadId;
This.startindex = StartIndex;
This.endindex = EndIndex;
This.path = path;
}


@Override
public void Run () {
Super.run ();
URL url;
try {
url = new URL (path);
HttpURLConnection connection = (httpurlconnection) URL
. OpenConnection ();
Request the server to download part of the file, set the start location, and end location
Connection.setrequestproperty ("Range", "bytes=" + startIndex
+ "-" + EndIndex);
Connection.setdoinput (TRUE);
Connection.setrequestmethod ("GET");
Connection.setreadtimeout (5000);
All data obtained from the server, return: 200, get some data from the server, return: 206
int code = Connection.getresponsecode ();
SYSTEM.OUT.PRINTLN ("code =" + code);
InputStream is = Connection.getinputstream ();
Randomaccessfile RAF = new Randomaccessfile ("Setup.exe", "RWD");
When the file is randomly written, when does it start?
Raf.seek (StartIndex);
int len = 0;
byte[] buff = new byte[1024];
while (len = is.read (buff))! =-1) {
Raf.write (buff, 0, Len);
}
Is.close ();
Raf.close ();
System.out.println ("Thread:" + threadId + ", download Complete");
} catch (Exception e) {
E.printstacktrace ();
}
}
}
}

To use this class, only need to know a URL address, and then call the inside of the Downfile () method, will start to download the file, so that the implementation can download an installation package, such as: Download a QQ on the internet, such as the installation package, installed on their own computer, you can use this method to achieve.

Android Multi-Threading Download principle

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.