Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 使用 AsyncTask 實現帶進度條的文件上傳示例

編輯:關於 Android 程式設計

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

demo 運行截圖:

AsyncTask 簡介

AsyncTask 是抽象類,子類必須實現抽象方法 doInBackground(Params... p),在此方法中實現任務的執行工作,比如聯網下載或上傳。它定義了三種泛型類型 Params、Progress 和 Result:

  1. Params:啟動任務執行的輸入參數,比如 HTTP 請求的 URL、上傳文件的路徑等;
  2. Progress:後台任務執行的百分比;
  3. Result:後台執行任務的最終返回結果,比如 String。

AsyncTask 的執行分為四個步驟,每一步對應一個回呼方法(這些方法不應由應用程序調用,而是由系統自動調用,開發者只需實作):

  1. onPreExecute():在執行實際後台操作前由 UI 線程調用,可做準備工作,如在界面顯示進度條。
  2. doInBackground(Params...):在 onPreExecute 執行後馬上執行,運行在後台線程,負責耗時的計算工作,可呼叫 publishProgress 更新實時進度。此為抽象方法,子類必須實作。
  3. onProgressUpdate(Progress...):在 publishProgress 被調用後,由 UI 線程調用,用於在界面展示任務進展,例如更新進度條。
  4. onPostExecute(Result):在 doInBackground 執行完成後由 UI 線程調用,將後台計算結果傳到 UI 線程。

主線程中啟動異步任務:

 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 即可。

以上就是本文的全部內容,希望對你的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved