The main UI thread is blocked when downloading files. Therefore, a new thread is required to perform the downloading operation. The handler is used to update the UI progress bar. The Code is as follows:
Public class androidtest extends activity {Private Static final string tag = "androidtest"; private progressbar = NULL; private button startbutton = NULL; private edittext filenametext = NULL; private myhandler handler = NULL; private Message message = NULL; private Boolean flag = true; private int size = 1; private int hasread = 0; private int Len = 0; private byte buffer [] = new byte [1024*4]; private int Index = 0; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); progressbar = (progressbar) findviewbyid (R. id. progress_horizontal); startbutton = (button) findviewbyid (R. id. mybutton); startbutton. setonclicklistener (New buttonclick (); filenametext = (edittext) findviewbyid (R. id. filenameid); handler = new m Yhandler ();} public Boolean downloadfile (final string urlstr, final string filename) {New thread (New runnable () {public void run () {try {URL url = new URL (urlstr); httpurlconnection connection = (httpurlconnection) URL. openconnection (); size = connection. getcontentlength (); inputstream = connection. getinputstream (); outputstream = new fileoutputstream (environment. getext Ernalstoragedirectory () + "/" + filename); While (LEN = inputstream. Read (buffer ))! =-1) {outputstream. write (buffer); hasread + = Len; Index = (INT) (hasread * 100)/size; message = new message (); message. what = 1; handler. sendmessage (Message); log. D (TAG, "Index =" + index); system. out. println ("has =" + hasread + "size =" + size + "Index =" + index);} inputstream. close (); outputstream. close ();} catch (exception e) {flag = false; E. printstacktrace ();}}}). start (); Return flag;} class Bu Ttonclick implements onclicklistener {public void onclick (view v) {string url = filenametext. gettext (). tostring (); string filename = URL. substring (URL. lastindexof ('/') + 1); log. D (TAG, "url =" + URL); log. D (TAG, "filename =" + filename); If (! Downloadfile (URL, filename) {string rs = "Download failed"; toast. maketext (androidtest. this, RS, toast. length_short ). show () ;}} class myhandler extends handler {@ override public void handlemessage (Message MSG) {If (MSG. what = 1) {progressbar. setprogress (INDEX); log. D (TAG, "setprogress index:" + index); If (index> = 99) {string rs = "Download complete"; toast. maketext (androidtest. this, RS, toast. length_short ). show () ;}} super. handlemessage (MSG );}}}
Turn: http://blog.csdn.net/ameyume/article/details/6183462