Android An example of uploading a picture, including how to terminate the upload process, if the upload time to update the progress bar (ii)

Source: Internet
Author: User

This can be achieved by uploading:

Activity in the execution:

Private class Uploadphototask extends asynctask<string, void, boolean>{    @Overrideprotected void OnPreExecute () {Super.onpreexecute ();} Protected Boolean doinbackground (String ... params) {    return httpuploadedfile.getinstance (). Douploadphoto ( Getapplicationcontext (), Muploadfilepathname, Mhandler);    }          protected void OnPostExecute (Boolean result) {    misuploading = false;    Showprogressbar (false); if (result) {Toast.maketext (Uploadphotoactivity.this, R.string.upload_photo_fail, Toast.length_short). Show ();} Else{toast.maketext (Uploadphotoactivity.this, R.string.upload_photo_fail, Toast.length_short). Show ();}}    


Write a handle to update the progress bar:

/** Handler to get notify from upload photo engine*/private Handler mhandler = new Handler () {@Overridepublic void Handlem Essage (Message msg) {switch (msg.what) {case HttpUploadedFile.POST_PROGRESS_NOTIFY:int completepercent = msg.arg1; Handleuploadprogress (completepercent); break;default:break;}}};/ * * Handle the uploading progress notification */private void handleuploadprogress (int completepercent) {View cont Ainerview = Findviewbyid (r.id.photo_upload_progress_bar_container); int maxlen = Containerview.getwidth (); <strong>//This is the width of the parent layout where the progress bar is located </strong>int barlen = (completepercent * maxlen)/100; View Barview = Findviewbyid (R.id.photo_upload_progress_bar); Layoutparams params = new Layoutparams ();p arams.height = Layoutparams.fill_parent;params.width = Barlen;  Barview.setlayoutparams (params); Update the width of the progress bar}/** * Show or hide progress bar */private void Showprogressbar (Boolean show) {View view = Findviewbyid (R . id.photo_upload_progress_layout); if (show) {View.setVisibility (view.visible); View bar = View.findviewbyid (R.id.photo_upload_progress_bar); Layoutparams params = new Layoutparams ();p arams.height = Layoutparams.fill_parent;params.width = 3;bar.setlayoutparams (params);} Else{view.setvisibility (View.gone);}}


The following are the uploaded modules:

public class Httpuploadedfile {/** A instance of this class */private static httpuploadedfile instance = null;/** * C Onstructor */private Httpuploadedfile () {}/** * Factory method */public static synchronized Httpuploadedfile getinstance ( {if (instance = = null) {instance = new Httpuploadedfile ();} return instance;} String url = "Http://2.novelread.sinaapp.com/framework-sae/index.php?c=main&a=getPostBody";p rivate int  Lasterrcode = 0;//Last error code byte[] Tmpbuf = new byte[buf_len];byte[] TmpBuf2 = new Byte[buf_len * 2];p ublic static final int post_progress_notify = 101; HttpURLConnection connection = null;public static final int http_argument_err = -1001;//HTTP parameter error public static final int Http_response_empty = -1002;//Http RESPONSE is//emptypublic static final int http_url_err = -1003;//URL format Error public Stati c final int http_gzip_err = -1004;//response data uncompressed failed public static final int http_canceled = -1005;//current Download canceled public static final int http_exception = -1006;//exception occurs private Boolean Bisstop = false;protected Object objabort = new Object ();p rivate Handler mhandler = null;public static final int TIMEOUT = 30000 ;//Timeout 30 seconds private static final int buf_len = 512;//Data buffer length public boolean douploadphoto (context context, String Filepathna Me,handler Handler) {Boolean ret = false; File File = new file (filepathname), if (!file.exists ()) {return false;} FileInputStream fs = null;if (file = null) {try {fs = new FileInputStream (file)} catch (FileNotFoundException e) {//TOD O auto-generated catch Blocke.printstacktrace ();}} if (file = = NULL | | fs = = NULL) {return false;} Mhandler = Handler;ret = Postwithoutresponse (context, URL, FS, (int) file.length ()), if (fs! = NULL) {try {fs.close (); fs = null;} catch (Exception e) {}}return ret;} Public Boolean Postwithoutresponse (context context, final String strurl,inputstream dataStream, int istreamlen) {<str ong>//<span style= "font-family:arial, Helvetica, Sans-serif;" The >istreamlen is the uppercase of the file, in bytes as the unit </span></strong>if (textutils.IsEmpty (strURL) | | DataStream = = NULL | | Istreamlen <= 0) {Lasterrcode = Http_argument_err;return false;} URL PostURL = null;try {posturl = new URL (strURL);} catch (Malformedurlexception ex) {LOG.E ("Httputil", "Get Malformedurl" , ex); lasterrcode = Http_url_err;return false;} Bisstop = False;inputstream input = Null;dataoutputstream ds = null; Bytearrayoutputstream byteoutstream = null; HttpURLConnection conn = null;byte[] Outdata = null;try {if (bisstop) {lasterrcode = Http_canceled;return false;} conn = getconnection (context, posturl); connection = Conn;conn.setrequestmethod ("POST"); Conn.setdoinput (true); Conn.setdooutput (True); Conn.setconnecttimeout (timeout * 3); Conn.setreadtimeout (timeout * 3); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Content-type", "application/ Octet-stream "); Conn.setrequestproperty (" Content-length ", String.valueof (Istreamlen)); if (bisstop) {LastErrCode = Http_canceled;return false;} Get the WiFi Statuswifimanager Wifimanager = (wifiManager) Context.getsystemservice (Context.wifi_service); Boolean bwifienable = (wifimanager.getwifistate () = = wifimanager.wifi_state_enabled);//byte[] data = new Byte[buf_len];d s = new DataOutputStream (Conn.getoutputstream ()); int len = 0;int Postlen = 0;int nmaxprogress = bwifienable? 80:40;while (!bisstop && (len = Datastream.read (TMPBUF2))! =-1)) {<strong>//If Bisstop is true, Then the process of writing the file to the server below terminates </strong>ds.write (tmpBuf2, 0, Len);d S.flush ();//Waiting for uploading the image file to optimize T He progress//Bar when using Gprsif (!bwifienable) {thread.sleep (30);} Notify post Progresspostlen + = Len;if (Mhandler! = null) {message msg = new Message (); msg.what = post_progress_notify;& LT;STRONG&GT;MSG.ARG1 = (Postlen * nmaxprogress)/Istreamlen;//postlen is the file size that has been uploaded, </strong><pre name= "code" Class= "Java" >nmaxprogress to increase the speed of the progress bar
Mhandler.sendmessage (msg);}} if (bisstop) {lasterrcode = Http_canceled;return false;} Ds.flush ();//Waiting for uploading the image file to optimize the progress bar//when using Gprsif (!bwifienable) {Postle n = 0;while (Postlen < Istreamlen) {Thread.Sleep (+);//Notify post Progresspostlen + = Tmpbuf2.length;if (Mhandler! = N ull) {Message msg = new Message (); msg.what = POST_PROGRESS_NOTIFY;MSG.ARG1 = (Postlen * +)/Istreamlen + 50;mhandler.sen dmessage (msg);}}} Waiting for the server's responseinputstream is = Conn.getinputstream (); int ch; StringBuffer res = new StringBuffer (), while ((ch = is.read ())! =-1) {res.append ((char) ch);} if (Mhandler! = null) {Message msg = new Message (); msg.what = Post_progress_notify;msg.arg1 = 90;mhandler.sendmessage (msg) ;} return true;} catch (Exception ex) {LOG.E ("Httputil", "POST", ex); if (bisstop) {lasterrcode = http_canceled;} else {lasterrcode = Http_e Xception;} return false;} Finally {try {outdata = null;if (input! = null) {input.close (); input = Null;} if (ds = null) {//Ds.close ();//ds = null;//}try {ds.close ();d s = null;} catch (Exception e) {//Todo:handle Excepti ON}IF (conn! = null) {conn.disconnect (); conn = null;} if (byteoutstream! = null) {byteoutstream.close (); byteoutstream = null;} if (bisstop) { //If the Cancel method is notified when the termination is completeSynchronized (objabort) {objabort.notify ();}} if (Mhandler! = null) {Message msg = new Message (); msg.what = Post_progress_notify;msg.arg1 = 100;mhandler.sendmessage (msg );}} catch (Exception ex) {LOG.E ("Httputil", "post finally", Ex);}}} Public synchronized void Cancel () {try { bisstop = true;//The user clicked the Cancel button, this setting bisstop trueif (connection! = null) {connection.disconnect (); connection = null;} synchronized (objabort) {///only
Postwithoutresponse execution to finally notifies you that the function is complete.
Objabort.wait (50);}} catch (Exception ex) {LOG.V ("Httputil", "Canel", Ex);}} Private HttpURLConnection getconnection (context context, URL url) throws Exception {string[] apninfo = null; Wifimanager Wifimanager = (wifimanager) context.getsystemservice (context.wifi_service); int wifiState = Wifimanager.getwifistate (); HttpURLConnection conn = null; conn = (httpurlconnection) url.openconnection ();//Get HTTP connectionReturn conn;}}


Code in http://download.csdn.net/detail/baidu_nod/7735511

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.