国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android帶進度條的文件上傳示例(使用AsyncTask異步任務)

2019-12-12 04:51:04
字體:
來源:轉載
供稿:網友

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

demo運行截圖:

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

1、Params 啟動任務執行的輸入參數,比如HTTP請求的URL,上傳文件的路徑等;

2、Progress 后臺任務執行的百分比;

3、Result 后臺執行任務的最終返回結果,比如String。

AsyncTask 的執行分為四個步驟,與前面定義的TaskListener類似。每一步都對應一個回調方法,需要注意的是這些方法不應該由應用程序調用,開發者需要做的就是實現這些方法。在任務的執行過程中,這些方法被自動調用。

1、onPreExecute(), 該方法將在執行實際的后臺操作前被UI thread調用。可以在該方法中做一些準備工作,如在界面上顯示一個進度條。

2、doInBackground(Params...), 將在onPreExecute 方法執行后馬上執行,該方法運行在后臺線程中。這里將主要負責執行那些很耗時的后臺計算工作。可以調用 publishProgress方法來更新實時的任務進度。該方法是抽象方法,子類必須實現。

3、onProgressUpdate(Progress...),在publishProgress方法被調用后,UI thread將調用這個方法從而在界面上展示任務的進展情況,例如通過一個進度條進行展示。

4、onPostExecute(Result), 在doInBackground 執行完成后,onPostExecute 方法將被UI thread調用,后臺的計算結果將通過該方法傳遞到UI thread.

主進程中使用下面兩行開始異步任務:

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 方城县| 汝城县| 施秉县| 黄冈市| 沙田区| 景洪市| 琼海市| 东至县| 招远市| 绩溪县| 黑龙江省| 丹寨县| 红安县| 聊城市| 叙永县| 尼玛县| 长武县| 绵阳市| 赞皇县| 山阳县| 马山县| 庄河市| 红原县| 白朗县| 定远县| 灌南县| 新安县| 大余县| 景洪市| 清河县| 乌拉特后旗| 巴林左旗| 新兴县| 漳平市| 焉耆| 梁河县| 景德镇市| 皮山县| 奈曼旗| 县级市| 二连浩特市|