An example of how android uploads an image, including how to terminate the upload process, if the progress bar is updated during the upload (2)
Upload can be implemented as follows:
Execute in activity:
private class UploadPhotoTask extends AsyncTask
{ @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 handle Y from upload photo engine */private Handler mHandler = new Handler () {@ Overridepublic void handleMessage (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 containerView = findViewById (R. id. photo_upload_progress_bar_container); int maxLen = containerView. getWidth ();// This is the width of the parent layout of the progress bar.Int barLen = (completePercent * maxLen)/100; View barView = findViewById (R. id. photo_upload_progress_bar); LayoutParams = new LayoutParams (); params. height = LayoutParams. FILL_PARENT; params. width = barLen; barView. setLayoutParams (params); // Update progress bar Width}/*** 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 = new LayoutParams (); params. height = LayoutParams. FILL_PARENT; params. width = 3; bar. setLayoutParams (params);} else {view. setVisibility (View. GONE );}}
The following is the upload module:
Public class HttpUploadedFile {/** single instance of this class */private static HttpUploadedFile instance = null;/*** Constructor */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 "; private int lastErrCode = 0; // The latest error code byte [] tmpBuf = new byte [BUF_LEN]; byte [] tmpBuf2 = new byte [BUF_LEN * 2]; public static final int post_progress_y y = 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; // public static final int HTTP_GZIP_ERR =-1004; // public static final int HTTP_CANCELED =-1005; // public static final int HTTP_EXCEPTION =-1006 has been canceled for the current download; // private boolean bIsStop = false; protected Object objAbort = new Object (); private Handler mHandler = null; public static final int TIMEOUT = 30000; // TIMEOUT 30 seconds private static final int BUF_LEN = 512; // data buffer length public boo Lean doUploadPhoto (Context context, String filePathName, 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) {// TODO 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 ){// IStreamLen is an uppercase object in bytes.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; Ht TpURLConnection 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-Typ E "," 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]; ds = new DataO UtputStream (conn. getOutputStream (); int len = 0; int postLen = 0; int nMaxProgress = bWifiEnable? 80: 40; while (! BIsStop & (len = dataStream. read (tmpBuf2 ))! =-1 )){// If the value of bIsStop is true, the process of writing a file to the server will be terminated.Ds. write (tmpBuf2, 0, len); ds. flush (); // waiting for uploading the image file to optimize the progress // bar when using uplsif (! BWifiEnable) {Thread. sleep (30);} // configure y post progresspostLen + = len; if (mHandler! = Null) {Message msg = new Message (); msg. what = POST_PROGRESS_NOTIFY;Msg. arg1 = (postLen * nMaxProgress)/iStreamLen; // postLen indicates the size of the uploaded file,NMaxProgress increases 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 uplsif (! BWifiEnable) {postLen = 0; while (postLen <iStreamLen) {Thread. sleep (30); // configure y post progresspostLen + = tmpBuf2.length; if (mHandler! = Null) {Message msg = new Message (); msg. what = POST_PROGRESS_NOTIFY; msg. arg1 = (postLen * 35)/iStreamLen + 50; mHandler. sendMessage (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_EXCEPTION;} return false ;} finally {try {outData = null; if (input! = Null) {input. close (); input = null;} // if (ds! = Null) {// ds. close (); // ds = null; //} try {ds. close (); ds = null;} catch (Exception e) {// TODO: handle exception} if (conn! = Null) {conn. disconnect (); conn = null;} if (byteOutStream! = Null) {byteOutStream. close (); byteOutStream = null;} if (bIsStop ){// If the termination is complete, the cancel method will be notified.Synchronized (objAbort) {objAbort. Y () ;}} 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 clicks the cancel button, and the value of bIsStop is true.If (connection! = Null) {connection. disconnect (); connection = null ;}Synchronized (objAbort) {// onlyPostWithoutResponse is executed to finally to notify you that this function can be executed.
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 (); // obtain the http ConnectionReturn conn ;}}
Code in http://download.csdn.net/detail/baidu_nod/7735511