最近項目中要做一個帶進度條的上傳文件的功能,學習了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即可。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答