Android--Multi-Threaded Download example (i)

Source: Internet
Author: User

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

When it comes to downloading files from Android, the Android API explicitly requires time-consuming operations to be executed in a sub-thread, and the download of the file is no doubt a lengthy one, so the download of the file is performed on the child thread. Below, we are working together to implement a small example of the use of multi-threaded download files in Android.

Second, the service side preparation

In this small example, I download the Youdao dictionary as an example, downloading the Youdao dictionary installation package on the Internet, creating a new Project Web in Eclipse, placing the downloaded Youdao Dictionary installation package in the WebContent directory, and publishing the project to Tomcat, as shown in


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 used to enter the path of the downloaded file in the network, a button, click the download file, a ProgressBar display the download progress, a textview display the percentage of downloads. The specific layout content is as follows:

<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. Custom Progressbarlistener Listener Interface

Create a new custom Progressbarlistener listener interface that defines two methods in this interface, 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, and the specific code is implemented as follows:

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

3. Custom Threading Class Downloadthread

This is done by inheriting the thread to implement the custom threading operation, in which the main implementation of the file download operation, in this class, defines a series of download-related instance variables to control the downloaded data, while through the custom listener Progressbarlistener in the Void The getdownload (int length) method to display the progress information with the new interface.

The specific implementation is as follows:

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;/** * Custom Threading class * @author Liuyazhuang * */public class Downloadthread extends thread {/ /download 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);//no longer determine if 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, calculate the number of threads per thread of data download, and so on.

The specific implementation is as follows:

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: Custom download File Listener interface * @throws Exception */public void Download (String path, P Rogressbarlistener 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 ();// Set 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 close 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 Intercept path * @param path: path to intercept file name * @return: Truncated file name */private string GetFileName (string path) {return Path.substri Ng (Path.lastindexof ("/") + 1);}}

5, Perfect mainactivity

In this class, we first find the individual controls in the page, implement the OnClick event of the button buttons, open a thread in the onclick event for the download operation, and the data obtained from the child threads, passed through the handler and message mechanism to the main thread, and the update interface is displayed.

The specific implementation is as follows:

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. Increase Permissions

Finally, don't forget to grant the app permission to use the Android Internet license and write files to the SD card.

The specific implementation is as follows:

<?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:targetsdkversion= "/><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:allowbacku P= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/ Apptheme "> <activity android:name=" com.example.multi.MainActivity "android:label=" @str Ing/app_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/&                Gt <category android:name= "Android.inteNt.category.LAUNCHER "/> </intent-filter> </activity> </application></manifes T>

Four, the Operation effect



Reminder: You can go to the http://download.csdn.net/detail/l1028386804/8899957 link to get the complete code sample

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android--Multi-Threaded Download example (i)

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.