Update UI Simple helper class when downloading files based on Android

Source: Internet
Author: User
Tags sendmsg

Because in the project development, there is such a simple need, ask Google, the network also has a lot of utils tools, but more redundant. I simply wrote a simple helper class.

/** * Download file, update UI Simple helper class * * @author jarlen * */ Public  class downloadhelper{    Private Static Final intDown_begin =0;Private Static Final intDown_updata =1;Private Static Final intDown_finish =2;Private Static Final intDown_error =3;PrivateContext Mcontext;PrivateTextView Mtextview;PrivateProgressBar MBar;PrivateHandler Handler =NewHandler () { Public void Handlemessage(Message msg) {if(! Thread.CurrentThread (). isinterrupted ()) {Switch(msg.what) { CaseDown_begin:if(Mtextview! =NULL) {Mtextview.settext ("Start Download"); }if(MBar! =NULL) {mbar.setprogress (0); } Break; CaseDown_updata:intfactor = MSG.ARG1;if(Mtextview! =NULL) {Mtextview.settext (factor +"%"); }if(MBar! =NULL) {mbar.setprogress (factor); } Break; CaseDown_finish:if(Mtextview! =NULL) {Mtextview.settext ("Download Complete"); }if(MBar! =NULL) {mbar.setprogress ( -); } Break; CaseDown_error:if(Mtextview! =NULL) {Mtextview.settext ("Download Error"); }if(MBar! =NULL) {mbar.setprogress (0); } Break;default: Break;    }            }        }; }; Public Downloadhelper(Context context) { This. Mcontext = Context; }/** * Set the UI to update when downloading TextView * @param View */     Public void Setupdataview(TextView view) { This. Mtextview = view; }/** * Set download, need to update the Ui,progressbar * @param Bar */     Public void Setupdatabar(ProgressBar bar) { This. MBar = bar; }/** * Start download * @param URL * file * @param Path * File Save address */     Public void Startdownload(FinalString URL,FinalString path) {NewThread () { Public void Run() {sendmsg (Down_begin,0);Try{Longdownloadsize = downloadupdatefile (URL, path);if(Downloadsize >0) {sendmsg (Down_finish,0); }                }Catch(Exception e)                    {E.printstacktrace (); Sendmsg (Down_error,0);        }            };    }.start (); }Private Long Downloadupdatefile(string down_url, String path)throwsException {intDown_step =1;//Hint step        intTotalSize;//Total file size        intDownloadcount =0;//already downloaded the good size        intUpdatecount =0;//File size that has been uploadedInputStream InputStream;        OutputStream OutputStream; URL url =NewURL (Down_url);        HttpURLConnection httpurlconnection = (httpurlconnection) URL. OpenConnection (); Httpurlconnection.setconnecttimeout ( -* +); Httpurlconnection.setreadtimeout ( -* +);//Get the size of the downloaded fileTotalSize = Httpurlconnection.getcontentlength ();if(Httpurlconnection.getresponsecode () = =404) {sendmsg (Down_error,0);Throw NewException ("fail!");        } InputStream = Httpurlconnection.getinputstream (); File dir =NewFile (path);if(!dir.exists ())        {Dir.mkdir (); } String name = Down_url.substring (Down_url.lastindexof ("/") +1, Down_url.length ()); File Updatefile =NewFile (dir, name); OutputStream =NewFileOutputStream (Updatefile,false);//File exists is overwritten        byteBuffer[] =New byte[1024x768];intReadSize =0; while((readsize = inputstream.read (buffer))! =-1) {outputstream.write (buffer,0, readsize); Downloadcount + = ReadSize;//Get the size downloaded to            //1% per growth            if(Updatecount = =0|| (Downloadcount * -/totalsize-down_step) >= updatecount) {updatecount + = Down_step;            Sendmsg (Down_updata, Updatecount); }        }if(HttpURLConnection! =NULL) {httpurlconnection.disconnect ();        } inputstream.close (); Outputstream.close ();returnDownloadcount; }Private void sendmsg(intFlagintFactor) {Message msg =NewMessage ();Switch(flag) { CaseDown_begin://Start         CaseDown_finish://Completed         CaseDown_error://Failure             Break; CaseDown_updata://Update progress barMsg.arg1 = factor; Break;default: Break;        } msg.what = Flag;    Handler.sendmessage (msg); }}

The use of simple description under;

new DownLoadHelper(this);helper1.setUpdataView(tv1);helper1.startDownLoad("http://img1.2345.com/appsimg/wallpaper/4/139460306960.jpg", path);

/********************************************/

Demo Source
http://download.csdn.net/detail/jarlen/8552443

Do not seriously check, there may be bugs, use the partner please own debug under, and notify me a bit, thank you

Update UI Simple helper class when downloading files based on Android

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.