編輯:關於 Android 程式設計
最近專案裡要做一個帶進度條的上傳文件功能,學習了 AsyncTask,用起來比較方便,只要實現幾個方法即可。另外做了一個簡單的 demo,希望能對大家有幫助,程序中設好文件路徑和服務器 IP 即可。
demo 運行截圖:


AsyncTask 是抽象類,子類必須實現抽象方法 doInBackground(Params... p),在此方法中實現任務的執行工作,比如聯網下載或上傳。它定義了三種泛型類型 Params、Progress 和 Result:
AsyncTask 的執行分為四個步驟,每一步對應一個回呼方法(這些方法不應由應用程序調用,而是由系統自動調用,開發者只需實作):
publishProgress 更新實時進度。此為抽象方法,子類必須實作。主線程中啟動異步任務:
mTask = new MyTask(); mTask.execute(filePath, url);
doInBackground() 中的 params[0] 和 params[1] 分別對應 execute() 的第一個和第二年變量。
private class MyTask extends AsyncTask<String, Integer, String>{ @Override protected void onPostExecute(String result) { //最終結果的顯示 mTvProgress.setText(result); } @Override protected void onPreExecute() { //開始前的准備工作 mTvProgress.setText("loading..."); } @Override protected void onProgressUpdate(Integer... values) { //顯示進度 mPgBar.setProgress(values[0]); mTvProgress.setText("loading..." + values[0] + "%"); } @Override protected String doInBackground(String... params) { //這裡 params[0] 和 params[1] 是 execute 傳入的兩個參數 String filePath = params[0]; String uploadUrl = params[1]; //下面即手機端上傳文件的代碼 String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setConnectTimeout(6*1000); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection .getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos .writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath.substring(filePath.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); //獲取文件總大小 FileInputStream fis = new FileInputStream(filePath); long total = fis.available(); byte[] buffer = new byte[8192]; // 8k int count = 0; int length = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); //獲取進度,調用 publishProgress() length += count; publishProgress((int) ((length / (float) total) * 100)); //這裡是測試時為了演示進度,休眠 500 毫秒,正常應去掉 Thread.sleep(500); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); @SuppressWarnings("unused") String result = br.readLine(); dos.close(); is.close(); return "上傳成功"; }catch (Exception e) { e.printStackTrace(); return "上傳失敗"; } }
界面中只要一個進度條 progressBar 和一個用於顯示的 TextView 即可。
以上就是本文的全部內容,希望對你的學習有所幫助。
Android 開發實例:打造 miniTwitter 登入介面
畫面規劃 本文以 miniTwitter 登入頁為例,示範如何用 Android 原生元件完成具有漸層背景、圓角卡片、輸入框與圖片的登入畫面。整體可拆成三個區塊:漸層背景
Android MediaRecorder 錄製音訊的實作流程
MediaRecorder 是 Android 錄製音訊的常用類別。透過設定音源、輸出格式、編碼器與檔案路徑,即可將麥克風輸入保存為音訊檔。 錄音流程 首先建立 Med
Android 中的訊息機制:從 Handler 源碼看子線程如何切換到主線程
寫部落格的時間,通常是晚上從圖書館回到宿舍之後,大約十一點半開始,一寫就到一兩點,而且這還是在素材積累得比較充分的情況下。寫完自己還得再看一遍才敢睡,隔天早上審稿後再發布
自定義 View 入門:跟著 TextView 源碼走一遍四步流程
關於 Android 自定義 View,網上的文章和視頻很多,鴻洋的系列教程就很值得一讀。本文的打算是結合影音系統源碼,把「如何自定義一個 View」這件事講透。 分析對