成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

Android中怎么利用AsyncTask實(shí)現(xiàn)下載文件動(dòng)態(tài)更新進(jìn)度條功能

Android中怎么利用AsyncTask實(shí)現(xiàn)下載文件動(dòng)態(tài)更新進(jìn)度條功能,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

創(chuàng)新互聯(lián)專注于竹山網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供竹山營銷型網(wǎng)站建設(shè),竹山網(wǎng)站制作、竹山網(wǎng)頁設(shè)計(jì)、竹山網(wǎng)站官網(wǎng)定制、微信小程序服務(wù),打造竹山網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供竹山網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

1. 泛型

AysncTask<Params, Progress, Result>

Params:啟動(dòng)任務(wù)時(shí)傳入的參數(shù),通過調(diào)用asyncTask.execute(param)方法傳入。

Progress:后臺(tái)任務(wù)執(zhí)行的進(jìn)度,若不用顯示進(jìn)度條,則不需要指定。

Result:后臺(tái)任務(wù)結(jié)束時(shí)返回的結(jié)果。

2. 重要方法

doInBackground(Params... params):必須重寫的方法,后臺(tái)任務(wù)就在這里執(zhí)行,會(huì)開啟一個(gè)新的線程。params為啟動(dòng)任務(wù)時(shí)傳入的參數(shù),參數(shù)個(gè)數(shù)不定。

onPreExecute():在主線程中調(diào)用,在后臺(tái)任務(wù)開啟前的操作在這里進(jìn)行,例如顯示一個(gè)進(jìn)度條對(duì)話框。

onPostExecute(Result result):當(dāng)后臺(tái)任務(wù)結(jié)束后,在主線程中調(diào)用,處理doInBackground()方法返回的結(jié)果。

onProgressUpdate(Progress... values):當(dāng)在doInBackground()中調(diào)用publishProgress(Progress... values)時(shí),返回主線程中調(diào)用,這里的參數(shù)個(gè)數(shù)也是不定的。

onCancelled():取消任務(wù)。

Android中怎么利用AsyncTask實(shí)現(xiàn)下載文件動(dòng)態(tài)更新進(jìn)度條功能

3. 注意事項(xiàng)

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

(2)AsyncTask實(shí)例必須在主線程中創(chuàng)建;

(3)不要手動(dòng)調(diào)用doInBackground()、onPreExecute()、onPostExecute()、onProgressUpdate()方法;

(4)注意防止內(nèi)存泄漏,在doInBackground()方法中若出現(xiàn)對(duì)Activity的強(qiáng)引用,可能會(huì)造成內(nèi)存泄漏。

4. 下載文件動(dòng)態(tài)更新進(jìn)度條(未封裝)

布局:

<?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"
    
    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實(shí)例必須在主線程創(chuàng)建
        DownloadAsyncTask asyncTask = new DownloadAsyncTask();
        asyncTask.execute(PDF_URL);
      }
    });
  }
  /**
   * 泛型:
   * String:傳入?yún)?shù)為文件下載地址
   * Integer:下載過程中更新ProgressBar的進(jìn)度
   * 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();//獲取內(nèi)容總長度
          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;//已經(jīng)下載的大小
          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. 下載文件動(dòng)態(tài)更新進(jìn)度條(封裝)

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 = "存儲(chǔ)路徑下的同名文件刪除失??!";
              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);
  }
}

看完上述內(nèi)容,你們掌握Android中怎么利用AsyncTask實(shí)現(xiàn)下載文件動(dòng)態(tài)更新進(jìn)度條功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

網(wǎng)站題目:Android中怎么利用AsyncTask實(shí)現(xiàn)下載文件動(dòng)態(tài)更新進(jìn)度條功能
分享路徑:http://jinyejixie.com/article12/jjjdgc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃定制開發(fā)、網(wǎng)站改版網(wǎng)站內(nèi)鏈、軟件開發(fā)、做網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設(shè)計(jì)
镇巴县| 巴里| 肇庆市| 钟山县| 鹿泉市| 东阿县| 嘉禾县| 丹棱县| 邓州市| 上饶市| 娄底市| 盖州市| 永和县| 玛沁县| 拉萨市| 修文县| 宿州市| 昌平区| 保山市| 渑池县| 多伦县| 自治县| 祁阳县| 图木舒克市| 于田县| 滦平县| 盐源县| 牟定县| 两当县| 手游| 富阳市| 灵台县| 清水县| 时尚| 阿鲁科尔沁旗| 阿拉善盟| 焦作市| 鄱阳县| 靖宇县| 息烽县| 临高县|