Android-Multi-Threaded Download Demo sample

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/46883927
I. Overview

Speaking of downloading files from Android. The Android API clearly requires time-consuming operations to be run in a sub-thread, and the download of the file will undoubtedly take a while. So you want to put the download of the file in a child thread to run.

Below, we work together to implement a sample of Android that uses multithreading to download files.

Second, the service side preparation

In this sample, I take the Youdao dictionary as an example. Download the Youdao dictionary installation package online and create a new Project Web in Eclipse. Place the downloaded Youdao Dictionary installation package under the WebContent folder and advertise the project to Tomcat in detail, for example, as seen in the


Third, Android implementation 1, layout

A textview is placed top-down on the interface to prompt for information entered in the text box. A text box is used to enter the path of the downloaded file in the network, a Buttonbutton, click Download File, a ProgressBar display the download progress, a textview display the percentage of downloads.

Detailed layout content such as the following:

<linearlayout 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 "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" Android:o rientation= "Vertical" tools:context= ".        Mainactivity "> <textview android:layout_width=" match_parent "android:layout_height=" Wrap_content " android:text= "Download path"/> <edittext android:id= "@+id/ed_path" android:layout_width= "Match_    Parent "android:layout_height=" wrap_content "android:text=" Http://192.168.0.170:8080/web/youdao.exe "/> <button android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "under Download "Android:onclick= "Download"/> <progressbar android:id= "@+id/pb" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" style= "@android: Style/widget.progressbar.horizontal"/> <TextVie         W android:id= "@+id/tv_info" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:gravity= "center" android:text= "Download: 0%"/></linearlayout>

2. Define your own Progressbarlistener listener interface

Create your own definition of the Progressbarlistener listener interface, which defines two methods, void Getmax (int length) to obtain the length of the downloaded file, void getdownload (int length); To get the length of each download, this method is mainly called in multi-threading, the data obtained in the sub-thread is passed to the two interface methods, and then the corresponding length information is passed to the main thread through handler in both interface methods, and the update interface displays the information. Detailed code implementations such as the following:

Package com.example.inter;/** * Self-defined progress bar listener * @author Liuyazhuang * */public interface Progressbarlistener {/** * get file length * @param length */void getmax (int length);/** * Gets the duration of each download * @param lengths */void getdownload (int length);}

3. Define Thread class Downloadthread

This is done by inheriting the thread to define the threading operation, in which the main implementation of the file is the download operation. In this class, you define a series of download-related instance variables to control the downloaded data, and at the same time use the void getdownload (int length) method in your own definition listener Progressbarlistener to display the progress information with the new interface.

Detailed implementations such as the following:

Package Com.example.download;import Java.io.file;import Java.io.fileoutputstream;import java.io.InputStream;import Java.io.randomaccessfile;import Java.net.httpurlconnection;import Java.net.url;import com.example.inter.progressbarlistener;/** * Define Thread class yourself * @author Liuyazhuang * */public class Downloadthread extends Thread { Downloaded thread idprivate int threadid;//downloaded file path private String path;//saved file Private files file;//download progress bar updated listener private Progressbarlistener listener;//The amount of data downloaded per thread private int block;//download start location private int startposition;//download end location private int Endposition;public downloadthread (int threadId, String path, file file, Progressbarlistener Listener, int block) {this.th Readid = Threadid;this.path = Path;this.file = File;this.listener = Listener;this.block = Block;this.startPosition = Threa did * block;this.endposition = (threadId + 1) * BLOCK-1;} @Overridepublic void Run () {super.run (); try {//Create Randomaccessfile object Randomaccessfile accessfile = new Randomaccessfile ( File, "RWD");//jump to start position Accessfile.seeK (startposition); URL url = new URL (path);//Open HTTP link httpurlconnection conn = (httpurlconnection) url.openconnection ();// Set the timeout time conn.setconnecttimeout (5000);//Specify the request mode as Get mode Conn.setrequestmethod ("get");//Specify the location of the download Conn.setrequestproperty ("Range", "bytes=" +startposition + "-" + endposition);//Do not infer whether the status code is 200InputStream in = Conn.getinputstream (); byte[] Buffer = new Byte[1024];int len = 0;while ((len = in.read (buffer))! =-1) {accessfile.write (buffer, 0, Len);//update download Progress Listener . Getdownload (len);} Accessfile.close (); In.close ();} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();}}}

4. New Downloadmanager class

This class is mainly for the management of the download process, including download settings after the download file to save the location. Calculates the amount of data downloaded for each thread in a multi-thread, and so on.

Detailed implementations such as the following:

Package Com.example.download;import Java.io.file;import Java.io.randomaccessfile;import java.net.HttpURLConnection ; Import java.net.url;import android.os.environment;import com.example.inter.progressbarlistener;/** * File download Manager * @ Author Liuyazhuang * */public class Downloadmanager {//number of download threads private static final int tread_size = 3;private File file;/* * * Download File Method * @param path: Download file path * @param listener: Self-defined download File Listener interface * @throws Exception */public void Download (String path, Progressbarlistener listener) throws Exception{url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"), if (conn.getresponsecode () = =) {int filesize = Conn.getcontentlength ();// Sets the maximum length of the progress bar Listener.getmax (filesize);//Create a file that is the same size as the server files = new (Environment.getexternalstoragedirectory () , This.getfilename (path)); Randomaccessfile accessfile = new Randomaccessfile (file, "RWD"); Accessfile.setlength (filesize);// To turn off the Randomaccessfile object acCessfile.close ();//Calculates the amount of data downloaded per thread int block = filesize% Tread_size = = 0? (filesize/tread_size): (Filesize/tread_size +1); Open thread download for (int i = 0; i < tread_size; i++) {New Downloadthread (I, path, file, Listener, block). Start ();}} /** * file name in the Intercept path * @param path: The path to intercept the file name * @return: The truncated file name */private string GetFileName (string path) {return path.substring ( Path.lastindexof ("/") + 1);}}

5, intact mainactivity

In this class, first, find the various controls in the page, implement the Buttonbutton onclick event, open a thread in the onclick event to download the operation, the same time the child thread to obtain the data, through the handler and message mechanism to the main thread, The update interface is displayed.

Detailed implementations such as the following:

Package Com.example.multi;import Android.app.activity;import Android.os.bundle;import android.os.Handler;import Android.os.message;import Android.view.menu;import Android.view.view;import Android.widget.edittext;import Android.widget.progressbar;import Android.widget.textview;import Android.widget.toast;import Com.example.download.downloadmanager;import com.example.inter.progressbarlistener;/** * mainactivity the entire application portal * @  Author Liuyazhuang * */public class Mainactivity extends Activity {protected static final int error_download = 0;protected static final int set_progress_max = 1;protected static final int update_progress = 2;private EditText ed_path;private Pro Gressbar pb;private TextView tv_info;private Downloadmanager manager;//handler operation private Handler Mhandler = new Handler () {public void Handlemessage (android.os.Message msg) {switch (msg.what) {case error_download://prompts user for download failure toast.maketext ( Mainactivity.this, "Download Failed", Toast.length_short). Show (); Break;case set_progress_max://get maximum value int max = (Integer) msg.obj;//sets the maximum value of the progress bar Pb.setmax (max); Break;case update_progress://Gets the length of the current download int currentprogress = Pb.getprogress ();//Gets the length of the new download int len = (Integer) msg.obj;//calculates the current total download length int crrrenttotalprogress = currentprogress + len; Pb.setprogress (crrrenttotalprogress);//Get total size int maxprogress = Pb.getmax ();//calculate percent float value = (float) Currentprogress/(float) maxprogress;int percent = (int) (value * 100);//Displays the percentage of downloads tv_info.settext ("Download:" +percent+ "%"); Break;default:break;};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); This.ed_path = (EditText) Super.findviewbyid (r.id.ed_path); THIS.PB = (ProgressBar) Super.findviewbyid (R.ID.PB); this.tv_info = (TextView) Super.findviewbyid (r.id.tv_info); This.manager = new Downloadmanager ();} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} Public void Download (View v) {Final String path = Ed_path.gettext (). toString ();//Download new Thread (new Runnable () {@Overridepublic V OID Run () {//TODO auto-generated method stubtry {manager.download (path, new Progressbarlistener () {@Overridepublic void G Etmax (int length) {//TODO auto-generated method Stubmessage message = new Message (); message.what = Set_progress_max;messa Ge.obj = length;mhandler.sendmessage (message);} @Overridepublic void getdownload (int length) {//TODO auto-generated method Stubmessage message = new Message (); MESSAGE.WH at = Update_progress;message.obj = length;mhandler.sendmessage (message);}});} catch (Exception e) {//Todo:handle exceptione.printstacktrace (); Message message = new Message (); message.what = error_download;mhandler.sendmessage (message);}}). Start ();}}

6. Add Permissions

Finally, don't forget to grant the app permission. This will use the Android network authorization and write files to the SD card permissions.

Detailed implementations such as the following:

<?xml version= "1.0" encoding= "Utf-8"?

><manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Com.example.multi" Android: Versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= "8" ANDROID:TARGETSD kversion= "/><uses-permission android:name=" Android.permission.INTERNET "/><uses-permission Android : Name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/> <application android:allowbackup=" true "android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "android:theme=" @style/apptheme "> <acti Vity android:name= "com.example.multi.MainActivity" android:label= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <categor Y android:name= "Android.intent.category.LAUNCHER"/> &Lt;/intent-filter> </activity> </application></manifest>

Iv. Effect of implementation



Reminder: You can go to the http://download.csdn.net/detail/l1028386804/8899957 link to get the full Code demo sample

Android-Multi-Threaded Download Demo sample

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.