Asynctask下載框架

        ***Asynctask下載框架***

注意execute方法的使用——–new AppAsyncTask().execute();

/**
 * 1. download方法  url localPath listener
 * 2. listener: start, success fail progress.
 * 3. 用asynctask封裝的
 * Created by renkangke on 16/12/19.
 */

public class DownloadHelper {


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


    public static class DownloadAsyncTask extends AsyncTask<String, Integer, Boolean> {
        String mUrl;
        String mFilePath;
        OnDownloadListener mListener;

        public DownloadAsyncTask(String url, String filePath, OnDownloadListener listener) {
            mUrl = url;
            mFilePath = filePath;
            mListener = listener;
        }
        /**
         * 在異步任務之前,在主線程中
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // 可操作UI  類似淘米,之前的準備工作
            if(mListener != null){
                mListener.onStart();
            }
        }
        /**
         * 在另外一個線程中處理事件
         * @param params 入參  煮米
         * @return 結果
         */
        @Override
        protected Boolean doInBackground(String... params) {
                String apkUrl = mUrl;

                try {
                    // 構造URL
                    URL url = new URL(apkUrl);
                    // 構造連接,並打開
                    URLConnection urlConnection = url.openConnection();
                    InputStream inputStream = urlConnection.getInputStream();
                    // 獲取了下載內容的總長度
                    int contentLength = urlConnection.getContentLength();
                    // 對下載地址進行處理
                    File apkFile = new File(mFilePath);
                    if(apkFile.exists()){
                        boolean result = apkFile.delete();
                        if(!result){
                            if(mListener != null){
                                mListener.onFail(-1, apkFile, "文件刪除失敗");
                            }
                            return false;
                        }
                    }
                    // 已下載的大小
                    int downloadSize = 0;
                    // byte數組
                    byte[] bytes = new byte[1024];
                    int length;
                    // 創建一個輸入管道
                    OutputStream outputStream = new FileOutputStream(mFilePath);
                    // 不斷的一車一車挖土,走到挖不到爲止
                    while ((length = inputStream.read(bytes)) != -1){
                        // 挖到的放到我們的文件管道里
                        outputStream.write(bytes, 0, length);
                        // 累加我們的大小
                        downloadSize += length;
                        // 發送進度
                        publishProgress(downloadSize * 100/contentLength);
                    }
                    inputStream.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    if(mListener != null){
                        mListener.onFail(-2, new File(mFilePath), e.getMessage());
                    }
                    return false;
                }

            if(mListener != null){
                mListener.onSuccess(0, new File(mFilePath));
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            // 也是在主線程中 ,執行結果 處理
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            // 收到進度,然後處理: 也是在UI線程中。
            if (values != null && values.length > 0) {
                if(mListener != null){
                    mListener.onProgress(values[0]);
                }
            }

        }

    }


    public interface OnDownloadListener{
        /**
         * 在接口出處理UI
         */

        void onStart();

        void onSuccess(int code, File file);

        void onFail(int code, File file, String message);

        void onProgress(int progress);


        abstract class SimpleDownloadListener implements OnDownloadListener{
            @Override
            public void onStart() {

            }

            @Override
            public void onProgress(int progress) {

            }
        }
    }

}
發佈了23 篇原創文章 · 獲贊 0 · 訪問量 4559
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章