Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android一個上傳圖片的例子,包括如何終止上傳過程,如果在上傳的時候更新進度條(二)

android一個上傳圖片的例子,包括如何終止上傳過程,如果在上傳的時候更新進度條(二)

編輯:關於Android編程

可以這樣來實現上傳:

activity中執行:

	private class UploadPhotoTask extends AsyncTask{
		
    	@Override
		protected 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();

			}
    	}
	}
	


寫一個handle來更新進度條:

/** Handler to get notify from upload photo engine*/
	private Handler mHandler = new Handler() {
		@Override
		public 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(); //這個是進度條所在的parent layout的寬度
		int barLen = (completePercent * maxLen) / 100;
		View barView = findViewById(R.id.photo_upload_progress_bar);
		LayoutParams params = new LayoutParams();
		params.height = LayoutParams.FILL_PARENT;
		params.width = barLen;
		barView.setLayoutParams(params);  //更新進度條的寬度
	}
	
	/**
     * 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();
			params.height = LayoutParams.FILL_PARENT;
			params.width = 3;
			bar.setLayoutParams(params);
		}else{
			view.setVisibility(View.GONE);
		}
	}


以下是上傳的模塊:

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;// 最近一次出錯的錯誤代碼
	byte[] tmpBuf = new byte[BUF_LEN];
	byte[] tmpBuf2 = new byte[BUF_LEN * 2];
	public static final int POST_PROGRESS_NOTIFY = 101;
	HttpURLConnection connection = null;
	public static final int HTTP_ARGUMENT_ERR = -1001;// HTTP 參數錯誤
	public static final int HTTP_RESPONSE_EMPTY = -1002;// Http Response is
														// Empty
	public static final int HTTP_URL_ERR = -1003;// Url格式錯誤
	public static final int HTTP_GZIP_ERR = -1004;// 響應數據解壓縮失敗
	public static final int HTTP_CANCELED = -1005;// 當前下載已取消
	public static final int HTTP_EXCEPTION = -1006;// 發生異常
	private boolean bIsStop = false;
	protected Object objAbort = new Object();

	private Handler mHandler = null;
	public static final int TIMEOUT = 30000;// 超時時間30秒
	private static final int BUF_LEN = 512;// 數據緩沖長度

	public boolean 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 block
				e.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是FIle的大寫,以字節作為單位

		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 status
			WifiManager wifiManager = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			boolean bWifiEnable = (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED);

			// byte[] data = new byte[BUF_LEN];
			ds = new DataOutputStream(conn.getOutputStream());
			int len = 0;
			int postLen = 0;
			int nMaxProgress = bWifiEnable ? 80 : 40;
			while (!bIsStop && ((len = dataStream.read(tmpBuf2)) != -1)) {//如果bIsStop為true,則下面寫文件到服務器的過程會終止
				ds.write(tmpBuf2, 0, len);
				ds.flush();
				// waiting for uploading the image file to optimize the progress
				// bar when using GPRS
				if (!bWifiEnable) {
					Thread.sleep(30);
				}

				// notify post progress
				postLen += len;
				if (mHandler != null) {
					Message msg = new Message();
					msg.what = POST_PROGRESS_NOTIFY;
					msg.arg1 = (postLen * nMaxProgress) / iStreamLen;//postLen是已經上傳的文件大小,
nMaxProgress 的作用上增快進度條
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) {postLen = 0;while (postLen < iStreamLen) {Thread.sleep(30);// notify 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) { //如果終止完成後會通知cancel那個方法synchronized (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;//用戶點擊了cancel button,這個設置bIsStop為trueif (connection != null) {connection.disconnect();connection = null;}synchronized (objAbort) { //只有
postWithoutResponse執行到finally才通知可以執行完這個函數
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();//獲取http的連接return conn;}}



代碼在http://download.csdn.net/detail/baidu_nod/7735511

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved