Zhao Yazhi _android Multi-threaded download with progress bar

Source: Internet
Author: User
Tags save file

ProgressBar Description

The visual indicator of progress in some operations, the progress of rendering the operation for the user, and also it has a secondary progress bar that is used to show the progress of intermediate progress, such as the buffer in streaming media playback.

A progress bar can also be uncertain about its progress. In indeterminate mode, the progress bar displays a looping animation. Such patterns are often used in applications where the length of the task is unknown.

XMLImportant Attributes

Android:progressbarstyle: Default progress bar Style

Android:progressbarstylehorizontal: Horizontal Style

ProgressBar Important methods

Getmax (): Returns the upper limit of the range of this progress bar

Getprogress (): return Progress

Getsecondaryprogress (): Returns secondary progress

Incrementprogressby (int diff): Specifies the progress of the addition

Isindeterminate (): Indicates whether the progress bar is in indeterminate mode

Setindeterminate (Boolean indeterminate): setting in indeterminate mode

setvisibility (int v): Sets whether the progress bar is visible

ProgressBar Important Events

onsizechanged (int w, int h, int oldw, int oldh): This event is raised when the progress value changes

Project implementation Step Analysis

1. Set the maximum value for the progress adjustment

2. Regardless of which thread is downloaded, record the current position of the progress bar and set the value

3. set Display current download value to TextView

4. Create a temporary file to record the location you have downloaded

5. Delete the file where the progress bar is temporarily saved when the thread has finished downloading

Main code: Join permissions

< uses-permission android:name="Android.permission.INTERNET"/>

< uses-permission android:name="Android.permission.WRITE_EXTERNAL_STORAGE"/>

< uses-permission android:name="Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

Layout file

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.android_download "android:versioncode=" 1 "android:versionname=" 1.0 "> <use S-SDK android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" Androi D.permission.internet "/> <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/> &lt ; uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <application android:allowb Ackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@st Yle/apptheme "> <activity android:name=" com.example.android_download. Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <caTegory android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application></manifest>

StreamtoolsTools

Android threads Download the same tool as http://blog.csdn.net/zhaoyazhi2129/article/details/27189465

ActivityMain code

Package Com.example.android_download;import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.inputstream;import Java.io.randomaccessfile;import Java.net.httpurlconnection;import Java.net.url;import Android.app.activity;import Android.os.Bundle;import Android.os.environment;import Android.text.textutils;import Android.view.view;import Android.widget.EditText; Import Android.widget.progressbar;import Android.widget.textview;import Android.widget.toast;import Com.example.util.streamtools;public class Mainactivity extends Activity {private int threadnum = 3;//thread open number private int t hreadrunning = 3;//executing thread private TextView tv_pb;private EditText et_url;private ProgressBar pb_download;private int cur rentpb;//Current value @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Findview (); File Sddir = Environment.getexternalstoragedirectory (); File Pdfile = new file (Sddir, "pb.txtInputStream is = null;try {//infer if the file exists if (pdfile.exists ()) {is = new FileInputStream (pdfile);}} catch (FileNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();} if (is! = null) {String value = Streamtools.streamtostr (IS);//split String arr[] = Value.split (";"); Pb_download.setmax (Integer.valueof (arr[0]));//Max CURRENTPB = integer.valueof (arr[1]);//Current Value Pb_ Download.setprogress (CURRENTPB); Tv_pb.settext ("The Current progress is:" +arr[2]);}} /** * */public void Findview () {TV_PB = (TextView) Findviewbyid (R.ID.TV_PB); Et_url = (EditText) Findviewbyid (R.id.et_url) ;p b_download = (ProgressBar) Findviewbyid (r.id.pb_download);} Download file (get server side file size) public void DownLoadFile (View v) {//Get download path final String spec = Et_url.gettext (). toString (); if (Tex Tutils.isempty (spec)) {Toast.maketext (this, "cannot be empty", 0). Show ();} else {new Thread () {@Overridepublic void Run () {//Access network address try {//Build URL object URL URL from downloaded address = new URL (spec);//Use the OpenConnection () method of the URL object to open the connection and return a Connection object httpurlconnection HttpURLConnection = (Httpurlconnection) url.openconnection ();//Set the request header Httpurlconnection.setrequestmethod ("GET"); Httpurlconnection.setconnecttimeout (Httpurlconnection.setreadtimeout (5000);//Infer if the response succeeds if ( Httpurlconnection.getresponsecode () = = 200) {/** * First step: Get the size of the server download file, and then set a temporary file on the local and server side file size consistent *///get file length int Filelength = Httpurlconnection.getcontentlength ();//Set the maximum value Pb_download.setmax (filelength) for the progress bar,//infer if the SD card is available if ( Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {//External storage device path File Sdfile = Environment.getexternalstoragedirectory ();//Gets the file name string filename = spec.substring (Spec.lastindexof ("/") +1);// Read and write random access files randomaccessfile (file, mode) randomaccessfile accessfile = new Randomaccessfile (new file (Sdfile, FileName) , "RWD");//Set temporary file size consistent with server file Accessfile.setlength (filelength);//Close Temporary file Accessfile.close ();/** * Step two: Calculate the size of each thread download (start position, end position) *///calculates the size of each thread download int threadsize = filelength/threadnum;//for loop, calculates the start and end positions for each thread for ( int threadId = 1; ThreadId <= 3; threadid++) {int STARtindex = (threadId-1) * threadsize;//start position int endIndex = ThreadId * threadsize-1;//End Position if (threadId = = threadnum) {/ /Last thread endindex = fileLength-1;} System.out.println ("Current thread--" + threadid+ "-----start position" + StartIndex + "----End position" + EndIndex + "-----Thread size" + threadsize);/** * Step three: Open thread download */new downloadthread (threadId, Startindex,endindex, spec,filename) every time you create it. Start ();}} else {runonuithread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtoast.maketext ( Mainactivity.this, "SD card does not exist", 1). Show ();}});}} else {runonuithread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtoast.maketext ( Mainactivity.this, "Server side returned error", 1). Show ();}});}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}. Start ();}} /** * Start thread download every time you create it * * @author Zhaoyazhi * */class Downloadthread extends Thread {//member variable private int threadid;private int startindex;private int endindex;private string path;private string fileName; File SdfilE = Environment.getexternalstoragedirectory ();/** * * @param threadId * Number of threads * @param startIndex * Thread Download Start location * @param endIndex * Thread download End location * @param path * Thread download save file Paths */public downloadthread (int threa did, int startIndex, int endindex,string path,string fileName) {super (); this.threadid = Threadid;this.startindex = Starti Ndex;this.endindex = Endindex;this.path = Path;this.filename = FileName;} @Overridepublic void Run () {//can be downloaded through each thread to download the file try {/** * Fourth step: Read the start position of the downloaded file from the local file */file recordfile = new File (Sdfile, Threa Did + ". txt"), if (Recordfile.exists ()) {//Read file InputStream is = new FileInputStream (recordfile);//Use tool class to convert string value = S Treamtools.streamtostr (IS);//Gets the location of the record int recordindex = Integer.parseint (value);//The position of the record is paid to start position startindex = Recordindex;} Constructs a URL object through the path object URL url = new URL (path),//through the URL object openconnectionhttpurlconnection httpurlconnection = ( httpurlconnection) url.openconnection ();//Set the request header Httpurlconnection.setrequestmethod ("GET"); HTTpurlconnection.setconnecttimeout (5000);//Set the start and end positions of the download file Httpurlconnection.setrequestproperty ("Range", "bytes= "+ StartIndex +"-"+ endIndex);//Get the status code int code = HTTPURLCONNECTION.GETRESPONSECODE ();//System.out.println (code);//Inference is No success just set the "Range" header, the returned status code is 206if (code = = 206) {//Gets the stream object returned by each thread inputstream is = Httpurlconnection.getinputstream ();// Create random Access Objects Randomaccessfile Accessfile = new Randomaccessfile (new File (Sdfile, FileName), "RWD");// Specify start position Accessfile.seek (startIndex);//define read length int len = 0;//define buffer byte buffer[] = new Byte[1024*1024];int total = 0;//Loop Read W Hile (len = is.read (buffer))! =-1) {System.out.println ("Current thread--" + threadid+ "-----The current download location is" + (StartIndex + total);//Warranty Save the download location for each thread randomaccessfile threadfile = new Randomaccessfile (new File (sdfile, ThreadId + ". txt"), "RWD");// Record each download location threadfile.writebytes ((StartIndex + total) + ""); Threadfile.close (); accessfile.write (buffer, 0, Len); Total + = len;//has downloaded size/** * When the program has multiple threads visiting a variable. able to solve */synchronized with synchronized (mainactivity. This) {//progress bar Current progress CURRENTPB + = len;pb_download.setprogress (CURRENTPB); final String percent= currentpb*100l/pb_ Download.getmax () + "%"; Runonuithread (new Runnable () {@Overridepublic void Run () {//Calculate percent Action Tv_pb.settext ("Current progress is:" + percent);}); /Create Save current progress and percentage randomaccessfile pbfile = new Randomaccessfile (new File (Sdfile, "Pb.txt"), "RWD");p Bfile.writebytes (pb_ Download.getmax () + ";" +currentpb+ ";" +percent);p bfile.close ();}} Accessfile.close (); Is.close (); Runonuithread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtoast.maketext (mainactivity.this, "current thread" + threadId + "---complete download", 1). Show ();}); * * Step Fifth: When your n threads are finished downloading, I do not delete the cache file of the record download location */deleterecordfile ();} else {runonuithread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtoast.maketext ( Mainactivity.this, "Server side returned error", 1). Show ();}}); Set your download file} catch (Exception e) {e.printstacktrace ();}}} /** * Synchronized Avoid thread synchronization download the temporary file that deletes the storage file download location */public synchronized void Deleterecordfile () {//External storageThe path of the device is file Sdfile = Environment.getexternalstoragedirectory ();//The thread is finished downloading minus threadrunning--;//when there is no executing thread if ( Threadrunning = = 0) {for (int i = 1; I <= 3; i++) {File Recordfile = (new File (sdfile, i + ". txt")); if (Recordfile.exis TS ()) {Recordfile.delete ();} File Pbfile = (new file (Sdfile, "Pb.txt")), if (Pbfile.exists ()) {Pbfile.delete ();}}}}

Complementary knowledge points

It is not necessary to consider synchronization when setting a value for the progress bar. sync is already set up due to android definition progressBar

2. When a program has multiple threads to access a variable, it can be resolved with synchronized

Synchronized (mainactivity.this) {//progress bar Current progress CURRENTPB + = len;pb_download.setprogress (CURRENTPB); Runonuithread (new Runnable () {@Overridepublic void run () {Tv_pb.settext ("Current progress is:" +currentpb*100/pb_download.getmax () + "%");}});


Execution results

1. when the file is downloaded, the progress bar display and the current progress display

2. continue the last download when loading again

3. when the file is downloaded, the pb.txt to temporarily store the downloaded file location is created

4. when the thread finishes downloading, the Toast on the main thread completes the Download

5. the progress bar is full at the moment and the current progress is 100%

6. after download, temporary file destruction



Source: http://download.csdn.net/detail/zhaoyazhi2129/7406731

Forwarding please indicate the source: http://blog.csdn.net/zhaoyazhi2129/article/details/27192169

Zhao Yazhi _android multithreaded download with progress bar

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.