AsyncTask用法解析-下載文件動態更新進度條

来源:http://www.cnblogs.com/joahyau/archive/2017/08/11/7344984.html
-Advertisement-
Play Games

1. 泛型 AysncTask Params:啟動任務時傳入的參數,通過調用asyncTask.execute(param)方法傳入。 Progress:後臺任務執行的進度,若不用顯示進度條,則不需要指定。 Result:後臺任務結束時返回的結果。 2. 重要方法 doInBackground(Pa ...


1. 泛型

AysncTask<Params, Progress, Result>

Params:啟動任務時傳入的參數,通過調用asyncTask.execute(param)方法傳入。

Progress:後臺任務執行的進度,若不用顯示進度條,則不需要指定。

Result:後臺任務結束時返回的結果。

2. 重要方法

doInBackground(Params... params):必須重寫的方法,後臺任務就在這裡執行,會開啟一個新的線程。params為啟動任務時傳入的參數,參數個數不定。

onPreExecute():在主線程中調用,在後臺任務開啟前的操作在這裡進行,例如顯示一個進度條對話框。

onPostExecute(Result result):當後臺任務結束後,在主線程中調用,處理doInBackground()方法返回的結果。

onProgressUpdate(Progress... values):當在doInBackground()中調用publishProgress(Progress... values)時,返回主線程中調用,這裡的參數個數也是不定的。

onCancelled():取消任務。

重要方法執行過程

3. 註意事項

(1)execute()方法必須在主線程中調用;

(2)AsyncTask實例必須在主線程中創建;

(3)不要手動調用doInBackground()、onPreExecute()、onPostExecute()、onProgressUpdate()方法;

(4)註意防止記憶體泄漏,在doInBackground()方法中若出現對Activity的強引用,可能會造成記憶體泄漏。

4. 下載文件動態更新進度條(未封裝)

佈局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp"
    tools:context="com.studying.asynctaskdemo.MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:progress="0" />

    <Button
        android:id="@+id/download"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="20dp"
        android:text="@string/start_btn" />

    <TextView
        android:id="@+id/status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="@string/waiting" />

</LinearLayout>

Activity:

public class MainActivity extends Activity {

    private static final String FILE_NAME = "test.pdf";//下載文件的名稱
    private static final String PDF_URL = "http://clfile.imooc.com/class/assist/118/1328281/AsyncTask.pdf";

    private ProgressBar mProgressBar;
    private Button mDownloadBtn;
    private TextView mStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initView();
        setListener();
    }

    private void initView() {
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mDownloadBtn = (Button) findViewById(R.id.download);
        mStatus = (TextView) findViewById(R.id.status);
    }

    private void setListener() {
        mDownloadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //AsyncTask實例必須在主線程創建
                DownloadAsyncTask asyncTask = new DownloadAsyncTask();
                asyncTask.execute(PDF_URL);
            }
        });
    }

    /**
     * 泛型:
     * String:傳入參數為文件下載地址
     * Integer:下載過程中更新ProgressBar的進度
     * Boolean:是否下載成功
     */
    private class DownloadAsyncTask extends AsyncTask<String, Integer, Boolean> {

        private String mFilePath;//下載文件的保存路徑

        @Override
        protected Boolean doInBackground(String... params) {
            if (params != null && params.length > 0) {
                String pdfUrl = params[0];

                try {
                    URL url = new URL(pdfUrl);
                    URLConnection urlConnection = url.openConnection();
                    InputStream in = urlConnection.getInputStream();
                    int contentLength = urlConnection.getContentLength();//獲取內容總長度

                    mFilePath = Environment.getExternalStorageDirectory() + File.separator + FILE_NAME;

                    //若存在同名文件則刪除
                    File pdfFile = new File(mFilePath);
                    if (pdfFile.exists()) {
                        boolean result = pdfFile.delete();
                        if (!result) {
                            return false;
                        }
                    }

                    int downloadSize = 0;//已經下載的大小
                    byte[] bytes = new byte[1024];
                    int length = 0;
                    OutputStream out = new FileOutputStream(mFilePath);
                    while ((length = in.read(bytes)) != -1) {
                        out.write(bytes, 0, length);
                        downloadSize += length;
                        publishProgress(downloadSize / contentLength * 100);
                    }

                    in.close();
                    out.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            } else {
                return false;
            }
            return true;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mDownloadBtn.setText("下載中");
            mDownloadBtn.setEnabled(false);
            mStatus.setText("下載中");
            mProgressBar.setProgress(0);
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            mDownloadBtn.setText("下載完成");
            mStatus.setText(aBoolean ? "下載完成" + mFilePath : "下載失敗");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (values != null && values.length > 0) {
                mProgressBar.setProgress(values[0]);
            }
        }
    }
}

5. 下載文件動態更新進度條(封裝)

Activity:

public class MainActivity extends Activity {

    private static final String FILE_NAME = "test.pdf";
    private static final String PDF_URL = "http://clfile.imooc.com/class/assist/118/1328281/AsyncTask.pdf";

    private ProgressBar mProgressBar;
    private Button mDownloadBtn;
    private TextView mStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initView();
        setListener();
    }

    private void initView() {
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mDownloadBtn = (Button) findViewById(R.id.download);
        mStatus = (TextView) findViewById(R.id.status);
    }

    private void setListener() {
        mDownloadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String localPath = Environment.getExternalStorageDirectory() + File.separator + FILE_NAME;
                DownloadHelper.download(PDF_URL, localPath, new DownloadHelper.OnDownloadListener() {
                    @Override
                    public void onStart() {
                        mDownloadBtn.setText("下載中");
                        mDownloadBtn.setEnabled(false);
                        mStatus.setText("下載中");
                        mProgressBar.setProgress(0);
                    }

                    @Override
                    public void onSuccess(File file) {
                        mDownloadBtn.setText("下載完成");
                        mStatus.setText(String.format("下載完成:%s", file.getPath()));
                    }

                    @Override
                    public void onFail(File file, String failInfo) {
                        mDownloadBtn.setText("開始下載");
                        mDownloadBtn.setEnabled(true);
                        mStatus.setText(String.format("下載失敗:%s", failInfo));
                    }

                    @Override
                    public void onProgress(int progress) {
                        mProgressBar.setProgress(progress);
                    }
                });
            }
        });
    }


}

DownloadHelper:

class DownloadHelper {

    static void download(String url, String localPath, OnDownloadListener listener) {
        DownloadAsyncTask task = new DownloadAsyncTask(url, localPath, listener);
        task.execute();
    }

    private static class DownloadAsyncTask extends AsyncTask<String, Integer, Boolean> {

        private String mFailInfo;

        private String mUrl;
        private String mFilePath;
        private OnDownloadListener mListener;

        DownloadAsyncTask(String mUrl, String mFilePath, OnDownloadListener mListener) {
            this.mUrl = mUrl;
            this.mFilePath = mFilePath;
            this.mListener = mListener;
        }

        @Override
        protected Boolean doInBackground(String... params) {
                String pdfUrl = mUrl;

                try {
                    URL url = new URL(pdfUrl);
                    URLConnection urlConnection = url.openConnection();
                    InputStream in = urlConnection.getInputStream();
                    int contentLength = urlConnection.getContentLength();

                    File pdfFile = new File(mFilePath);
                    if (pdfFile.exists()) {
                        boolean result = pdfFile.delete();
                        if (!result) {
                            mFailInfo = "存儲路徑下的同名文件刪除失敗!";
                            return false;
                        }
                    }

                    int downloadSize = 0;
                    byte[] bytes = new byte[1024];
                    int length;
                    OutputStream out = new FileOutputStream(mFilePath);
                    while ((length = in.read(bytes)) != -1) {
                        out.write(bytes, 0, length);
                        downloadSize += length;
                        publishProgress(downloadSize / contentLength * 100);
                    }

                    in.close();
                    out.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    mFailInfo = e.getMessage();
                    return false;
                }
            return true;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mListener != null) {
                mListener.onStart();
            }
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (mListener != null) {
                if (aBoolean) {
                    mListener.onSuccess(new File(mFilePath));
                } else {
                    mListener.onFail(new File(mFilePath), mFailInfo);
                }
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (values != null && values.length > 0) {
                if (mListener != null) {
                    mListener.onProgress(values[0]);
                }
            }
        }
    }

    interface OnDownloadListener{
        void onStart();
        void onSuccess(File file);
        void onFail(File file, String failInfo);
        void onProgress(int progress);
    }
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 參考資料:http://blog.csdn.net/ElinaVampire/article/details/51813677 大家先看一張關於組件掛載的經典的圖片: 下麵一一說一下這幾個生命周期的意義: getDefaultProps object getDefaultProps() 執行過一次後 ...
  • 標識符命名法最要有四種: Camel(駱駝)命名法:除首單詞外,其餘所有單詞的第一個字母大寫,如:fooBar; Pascal命名法:所有單詞的第一個字母大寫,如:FooBar; 下劃線命名法:單詞與單詞間用下劃線做間隔,如:foo_bar; 匈牙利命名法:廣泛應用於微軟編程環境中,在以Pascal ...
  • 1.developer.apple.com 申請開發者賬號 2.根據API Cloud創建證書: http://docs.apicloud.com/Dev-Guide/iOS-License-Application-Guidance 3.iTunes Connect上面新建APP 4. 下載 APP ...
  • 效果圖如下 1、自定義屬性,在value文件夾下新建attrs文件,聲明如下屬性 2、繼承ImageView ,重寫構造和ondraw方法 3、引入CircleImageView ...
  • Android MediaRecorder自定義解析度 工作這麼久了,確實積累了不少東西,但都是以文檔的形式存在U盤裡的,為什麼不寫博客呢?因為懶啊!!!總感覺博客太難寫了(大概是上學時候寫作文恐懼症 的後遺症吧……),不過現在看看那些積累的有些是自己總結,但也有不少是綜合網上各位大佬的文章提煉出來 ...
  • Android Studio 是個發工具,其自身帶調式環境是很強大的,我們要擺脫只會使用Log列印日誌的低效的方法,掌握高級調試技巧對每個Android開發者都是很必要的,廢話少說,直入正題 調試方式:通過下麵方法進入調試 運行調試:點擊齒輪運行按鈕,IDE出現調試視窗; 附加進程: 如果App正在 ...
  • 近期在做一個答題類型的APP,而其中最重要的是答題卡。而答題卡要如何做? 1.將數據插入到SQLite資料庫中 2.建立entity實體包,創建實體類,封裝。 3.創建實體與view的List集合 4.迴圈讀取數據,加入到實體集合中 5.根據實體集合(size)進行迴圈,將佈局文件轉化為view,加 ...
  • 1、創建應用 獲取AK (我理解為Application key) 通過百度賬號登錄百度地圖開放平臺,進入API控制台 http://lbsyun.baidu.com/apiconsole/key 創建自己的應用,輸入應用名稱 ,選擇Android SDK 應用類型,選擇需要的服務(預設全選) 輸入 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...