Android multi-Threaded Download Instance _android

Source: Internet
Author: User
Tags flush gettext int size
Copy Code code as follows:

public class Mainactivity extends activity {
declaring controls
Path and number of threads
Private EditText Et_url, Et_num;
Progress bar
public static ProgressBar Pb_thread;
Actions that show progress
Private TextView TV_PB;
Number of threads
public static int threadnum = 3;
Each thread is responsible for the size of the download
public int blockSize;
Number of public static int threadcount;//
Access to Path
public String Path;
public static Boolean flag = TRUE;
Record the value of a 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;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Et_url = (edittext) Findviewbyid (R.id.et_path);
Et_num = (edittext) Findviewbyid (r.id.et_threadnum);
Pb_thread = (ProgressBar) Findviewbyid (R.id.pb_down);
TV_PB = (TextView) Findviewbyid (R.ID.TV_PB);
Handler = new Handler () {
@Override
public void Handlemessage (msg) {
Super.handlemessage (msg);
Switch (msg.what) {
Case TextValue:
System.out.println ("-----------------------"
+ Mainactivity.pb_count + "//////"
+ mainactivity.size);

Change TextView
Pb_num = (Mainactivity.pb_count *)/mainactivity.size;
Tv_pb.settext ("Current progress is +" + pb_num + "%");
Break
Default
Break
}
}
};
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.down, menu);
return true;
}
Download action
public void DownLoad (View v) {
To change the value of a variable:
Mainactivity.flag = true;
Mainactivity.pb_count = 0;
Path = Et_url.gettext (). toString ();
String Threadnum_et = Et_num.gettext (). toString ();
if (textutils.isempty (path) | | Textutils.isempty (Threadnum_et)) {
Toast.maketext (This, "cannot be empty", Toast.length_long). Show ();
Return
}
Toast.maketext (This, "URL:" + path + "--" + Threadnum_et,
Toast.length_long). Show ();
Convert to Number
Threadnum = integer.valueof (Threadnum_et);
New Thread (New Runnable () {
@Override
public void Run () {
try {
Create a URL object
URL url = new URL (path);
Create a HttpURLConnection object
HttpURLConnection httpurlconnection = (httpurlconnection) URL
. OpenConnection ();
Set how send requests are sent
Httpurlconnection.setrequestmethod ("get");
Set whether the request is timed out
Httpurlconnection.setconnecttimeout (5000);
Set up
HttpURLConnection
. Setrequestproperty ("User-agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; trident/6.0) ");
Whether to respond successfully
if (httpurlconnection.getresponsecode () = = 200) {
Get the size of a file
Size = Httpurlconnection.getcontentlength ();
SYSTEM.OUT.PRINTLN ("Size of file" + sizes);
Set the maximum of a progress bar
Pb_thread.setmax (size);
Create File//Save to SD card
First, determine if you have SDcard
if (Environment.getexternalstoragestate (). Equals (
environment.media_mounted)) {
Get sdcard File directory object
File sdfile = Environment
. getExternalStorageDirectory ();
Create a File object
File File = new file (sdfile, "Youdao.exe");
Randomaccessfile accessfile = new Randomaccessfile (
File, "RWD");
To set the size of a file
Accessfile.setlength (size);
The size of each thread download
BlockSize = Size/threadnum;
Open three threads to manipulate this file
for (int i = 1; I <= threadnum; i++) {
1 2 3
To calculate where each thread starts
int startsize = (i-1) * blockSize;
End Position
int endsize = (i) * blockSize;
When the thread is the last thread
if (i = = threadnum) {
Determines whether the file size is greater than the computed end position
if (Size > Endsize) {
The end position equals the size of the file
endsize = size;
}
}
Create a random read for each thread
Randomaccessfile threadaccessfile = new Randomaccessfile (
File, "RWD");
New Thread (New Downloadthread (i),
Threadaccessfile, Startsize, Endsize,
Path)). Start ();
}
}
}
catch (Malformedurlexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
). Start ();
}
Pause operation
public void Downpause (View v) {
Toast.maketext (this, pause, Toast.length_long). Show ();
This.flag = false;
}
}

Copy Code code as follows:

public class Downloadthread implements Runnable {
Packaging for downloading files
Public Randomaccessfile Accessfile;
The starting position of the thread download file
public int startsize;
public int endsize;
Path to file downloads
public String Path;
public int threadId; Identification of threads
Public downloadthread (int threadId, Randomaccessfile accessfile,
int startsize, int endsize, String path) {
This.threadid = threadId;
This.accessfile = Accessfile;
This.startsize = startsize;
This.endsize = endsize;
This.path = path;
}
@Override
public void Run () {
Execute the Run method
try {
Create file to SD card
First, determine if you have SDcard
if (Environment.getexternalstoragestate (). Equals (
environment.media_mounted)) {
Get sdcard File directory object
File sdfile = Environment.getexternalstoragedirectory ();
File Threadfile = new file (sdfile, ThreadId + ". txt");
if (threadfile.exists ()) {
Read the contents of the file
Create an input stream object for a file
FileInputStream fis = new FileInputStream (threadfile);
Use tool class to read
byte data[] = Streamtools.istodata (FIS);
Into strings
String threadlen = new string (data);
if (Threadlen!= null) && (! "". Equals (Threadlen))) {
Startsize = integer.valueof (Threadlen);
Troubleshoot 416bug errors
if (Startsize > Endsize) {
Startsize = endSize-1;
}
}
}
Create a file
Create a URL object
URL url = new URL (path);
Creating HttpURLConnection Objects
HttpURLConnection httpurlconnection = (httpurlconnection) URL
. OpenConnection ();
Set the header of the request
Httpurlconnection.setrequestmethod ("get");
Set whether the request is timed out
Httpurlconnection.setconnecttimeout (5000);
Set up
HttpURLConnection
. Setrequestproperty ("User-agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; trident/6.0) ");
The key settings
Httpurlconnection.setrequestproperty ("Range", "bytes=")
+ startsize + "-" + endsize);
Output Current thread
System.out.println ("Current thread" + threadId + "Download start position:" + startsize
+ "Download End location:" + endsize);
Response successful
Set the starting position of random read files
Accessfile.seek (startsize);
Get the corresponding Stream object
InputStream is = Httpurlconnection.getinputstream ();
Creating an output Stream object
byte buffer[] = new byte[1024];
int len = 0;
int threadtotal = 0;//Save record after each thread download
while (len = is.read (buffer))!=-1) {
Accessfile.write (buffer, 0, Len);
Threadtotal + = len;//Record the length//xml file you write
Change the progress bar:
Setprogressbar (len);
The length of the file download through the document record
FileOutputStream fos = new FileOutputStream (threadfile);
Fos.write ((Threadtotal + ""). GetBytes ());
Fos.flush ();
Fos.close ();
Send Handler message
MainActivity.handler.sendEmptyMessage (Mainactivity.textvalue);
if (! Mainactivity.flag) {
Return
}
}
Accessfile.close ();
Is.close ();
System.out.println (threadId + "thread execution complete");
Threading actions
Synchronized (Mainactivity.class) {
mainactivity.threadcount++;
if (Mainactivity.threadcount >= mainactivity.threadnum) {
for (int i = 1; I <= mainactivity.threadnum; i++) {
Get the files on the SDcard
File DeleteFile = new file (sdfile, i + ". txt");
if (deletefile.exists ()) {
File deletion
Deletefile.delete ();
}
}
}
}
}
catch (Malformedurlexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}



Public synchronized void Setprogressbar (int len) {
Mainactivity.pb_count+=len;
MainActivity.pb_thread.setProgress (Mainactivity.pb_count);
}



}

Copy Code code as follows:

public class Streamtools {

public static byte[] Istodata (InputStream is) throws ioexception{
BYTE output stream
Bytearrayoutputstream Bops = new Bytearrayoutputstream ();
Read cache of data
byte buffer[] = new byte[1024];
Read the length of the record
int len = 0;
Looping read
while (len = is.read (buffer))!=-1) {
Bops.write (buffer, 0, Len);
}
Converts the read content into a byte array
byte data[] = Bops.tobytearray ();

Bops.flush ();
Bops.close ();
Is.close ();
return data;
}
}

Complete source
Related Article

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.