If you want to implement a download function, of course, the ideal function must support multi-task simultaneous download and resumable download, I want to step by step, first of all, the difficulty lies in the multi-task here.
My idea is to start the download stream operation in a service, and then declare a handler in the activity in the service to update the UI (such as the progress bar ...)
However, I found that the handler in an activity cannot be declared in the Service (maybe I can't do it, but I cannot apply for memory)
Therefore, I decided to directly start the thread in the activity, let it run, and call its own handler to update the UI. I did not expect that the thread was still active during the download of activity onpause, that is to say, you can continue the download. The next example is a small example of simultaneous download of two tasks. The ideal functions will be added later...
Main. xml configuration:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><ProgressBar style="?android:attr/progressBarStyleHorizontal"android:layout_height="wrap_content" android:id="@+id/progressBar1"android:layout_width="fill_parent"></ProgressBar><TextView android:layout_width="fill_parent" android:id="@+id/textView1"android:layout_height="wrap_content" /><ProgressBar style="?android:attr/progressBarStyleHorizontal"android:layout_height="wrap_content" android:id="@+id/progressBar2"android:layout_width="fill_parent"></ProgressBar><TextView android:layout_width="fill_parent" android:id="@+id/textView2"android:layout_height="wrap_content" /></LinearLayout>
Androidmanifest. xml configuration:
<? XML version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: Android = "http://schemas.android.com/apk/res/android" package = "SMS. down "Android: versioncode =" 1 "Android: versionname =" 1.0 "> <uses-SDK Android: minsdkversion =" 9 "/> <application Android: icon = "@ drawable/icon" Android: Label = "@ string/app_name"> <activity Android: Name = ". multhreaddownload "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> <! -- Access Internet permissions --> <uses-Permission Android: Name = "android. permission. internet "/> <uses-Permission Android: Name =" android. permission. call_phone "/> <uses-Permission Android: Name =" android. permission. send_sms "/> <uses-Permission Android: Name =" android. permission. read_contacts "/> <uses-Permission Android: Name =" android. permission. write_external_storage "/> <uses-Permission Android: Name =" android. permission. mount_unmount_filesystems "/> <uses-Permission Android: Name =" android. permission. read_phone_state "/> </manifest>
Activity program:
Package SMS. down; import Java. io. file; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; import java.net. httpurlconnection; import java.net. malformedurlexception; import java.net. URL; import android. app. activity; import android. OS. bundle; import android. OS. environment; import android. OS. handler; import android. OS. message; import android. widget. P Rogressbar; import android. widget. textview; public class multhreaddownload extends activity {/** called when the activity is first created. */private progressbar PB1 = NULL; private textview TV1 = NULL; private progressbar PBS = NULL; private textview TV2 = NULL; private string root = environment. getexternalstoragedirectory (). getabsolutepath () + file. separator; private string downloadfile = "http: // gongx Declare "; private string downloadfile1 =" http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3 "; // declare the length variable private int hasread = 0; Public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); PB1 = (progressbar) findviewbyid (R. id. progressbar1); TV1 = (textview) f Indviewbyid (R. id. textview1); PBS = (progressbar) findviewbyid (R. id. progressbar2); TV2 = (textview) findviewbyid (R. id. textview2); download (downloadfile, root, PB1, TV1); download (downloadfile1, root, CD2, TV2);} private void download (string URL, string targetpath, progressbar Pb, textview TV) {downloadthread dt = new downloadthread (URL, targetpath, Pb, TV); DT. start () ;}// customize a handler class to process the thread message public class Myhandler extends handler {private progressbar; private textview; // you can use the constructor to determine which progressbar to refresh public myhandler (progressbar, textview) {This. progressbar = progressbar; this. textview = textview;} public void handlemessage (Message MSG) {This. progressbar. setprogress (MSG. arg1); this. textview. settext (MSG. arg1 + "%"); super. handlemessage (MSG) ;}// download thread public class down Loadthread extends thread {private string url = ""; private string targetpath = ""; private int hasdownload = 0; private int Len =-1; private byte buffer [] = new byte [4*1024]; private int size = 0; private int rate = 0; private myhandler = NULL; private message MSG = NULL; private progressbar Pb = NULL; private textview TV = NULL; Public downloadthread (string URL, string targetpath, progressbar PB, textview TV) {This. url = url1_this.tar getpath = targetpath; this. PB = Pb; this. TV = TV; myhandler = new myhandler (this. PB, this. TV);} public void run () {string targetfilename = this.tar getpath + this. URL. substring (this. URL. lastindexof ("/") + 1, this. URL. length (); file downloadfile = new file (targetfilename); If (! Downloadfile. exists () {try {downloadfile. createnewfile ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}try {URL fileurl = new URL (this. URL); httpurlconnection conn = (httpurlconnection) fileurl. openconnection (); // obtain the file size. size = Conn. getcontentlength (); inputstream is = Conn. getinputstream (); outputstream OS = new fileoutputstream (targetfilename); While (LEN = is. read (Buffer ))! =-1) {OS. write (buffer); hasdownload + = Len; rate = (hasdownload * 100/size); MSG = new message (); MSG. arg1 = rate; myhandler. sendmessage (MSG); system. out. println (rate + "%") ;}} catch (malformedurlexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();}}}}
Program running effect:
Source code download
The next step will enable resumable upload and pause deletion. For more updates, please stay tuned ....
Reprinted please indicate the source of http://blog.csdn.net/shimiso technology exchange group: 173711587