亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

android使用AsyncTask實(shí)現(xiàn)多線程下載實(shí)例

 更新時(shí)間:2017年02月07日 17:28:13   作者:RickGe  
這篇文章主要介紹了android使用AsyncTask實(shí)現(xiàn)多線程下載實(shí)例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

AsyncTask不僅方便我們?cè)谧泳€程中對(duì)UI進(jìn)行更新操作,還可以借助其本身的線程池來實(shí)現(xiàn)多線程任務(wù)。下面是一個(gè)使用AsyncTask來實(shí)現(xiàn)的多線程下載例子。

01 效果圖

02 核心類 - DownloadTask.class

public class DownloadTask extends AsyncTask<String, Integer, Integer> {
  public static final int TYPE_SUCCESS = 0;
  public static final int TYPE_FAILURE = 1;
  public static final int TYPE_PAUSE = 2;
  public static final int TYPE_CANCEL = 3;

  public int positionDownload;

  private boolean isPaused = false;
  private boolean isCancelled = false;

  private DownloadListener downloadListener;
  private int lastProgress;

  public DownloadTask(DownloadListener downloadListener){
    this.downloadListener = downloadListener;
  }

  public void setDownloadListener(DownloadListener downloadListener){
    this.downloadListener = downloadListener;
  }

  @Override
  protected Integer doInBackground(String... params) {
    InputStream is = null;
    RandomAccessFile savedFile = null;
    File file = null;

    long downloadLength = 0;
    String downloadUrl = params[0];
    positionDownload = Integer.parseInt(params[1]);
    String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
    String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
    file = new File(directory + fileName);

    if(file.exists()){
      downloadLength = file.length();
    }

    long contentLength = getContentLength(downloadUrl);
    if(contentLength == 0){
      return TYPE_FAILURE;
    } else if(contentLength == downloadLength){
      return TYPE_SUCCESS;
    }

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
                  .addHeader("RANGE", "bytes="+downloadLength+"-")
                  .url(downloadUrl)
                  .build();
    try {
      Response response = client.newCall(request).execute();
      if(response != null){
        is = response.body().byteStream();
        savedFile = new RandomAccessFile(file, "rw");
        savedFile.seek(downloadLength);
        byte[] buffer = new byte[1024];
        int total = 0;
        int length;

        while((length = is.read(buffer)) != -1){
          if(isCancelled){
            response.body().close();
            return TYPE_CANCEL;
          } else if(isPaused) {
            response.body().close();
            return TYPE_PAUSE;
          }

          total += length;
          savedFile.write(buffer, 0, length);

          int progress = (int) ((total + downloadLength) * 100 / contentLength);
          int currentDownload = (int) (total + downloadLength);
          publishProgress(positionDownload, progress, currentDownload, (int) contentLength);
        }

        response.body().close();
        return TYPE_SUCCESS;
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if(is != null) is.close();
        if(savedFile != null) savedFile.close();
        if(isCancelled && file != null) file.delete();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return TYPE_FAILURE;
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
    int progress = values[1];
    if(progress > lastProgress){
      downloadListener.onProgress(values[0], progress, values[2], values[3]);
      lastProgress = progress;
    }
  }

  @Override
  protected void onPostExecute(Integer status) {
    switch (status){
      case TYPE_SUCCESS:
        downloadListener.onSuccess(positionDownload);
        break;
      case TYPE_FAILURE:
        downloadListener.onFailure();
        break;
      case TYPE_PAUSE:
        downloadListener.onPause();
        break;
      case TYPE_CANCEL:
        downloadListener.onCancel();
        break;
    }
  }

  public void pauseDownload(){
    isPaused = true;
  }

  public void cancelDownload(){
    isCancelled = true;
  }

  private long getContentLength(String downloadUrl) {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
                  .url(downloadUrl)
                  .build();
    Response response = null;
    try {
      response = client.newCall(request).execute();
      if(response != null && response.isSuccessful()){
        long contentLength = response.body().contentLength();
        response.body().close();
        return contentLength;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    return 0;
  }
}

03 核心類 - DownloadService.class

public class DownloadService extends Service {
  private Map<String, DownloadTask> downloadTaskMap = new HashMap<>();

  private DownloadBinder mBinder = new DownloadBinder();

  @Override
  public IBinder onBind(Intent intent) {
    return mBinder;
  }

  private Notification getNotification(String title, int progress) {
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
    builder.setContentIntent(pendingIntent);
    builder.setContentTitle(title);
    if(progress > 0){
      builder.setContentText(progress + "%");
      builder.setProgress(100, progress, false);
    }


    return builder.build();
  }

  private NotificationManager getNotificationManager() {
    return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  }


  class DownloadBinder extends Binder {
    public void startDownload(String url, int position, DownloadListener listener){
      if(!downloadTaskMap.containsKey(url)){
        DownloadTask downloadTask = new DownloadTask(listener);
        downloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url, position+"");
        downloadTaskMap.put(url, downloadTask);
        if(downloadTaskMap.size() == 1){
          startForeground(1, getNotification("正在下載" + downloadTaskMap.size(), -1));
        } else{
          getNotificationManager().notify(1, getNotification("正在下載" + downloadTaskMap.size(), -1));
        }
      }
    }

    public void updateDownload(String url, DownloadListener listener){
      if(downloadTaskMap.containsKey(url)){
        DownloadTask downloadTask = downloadTaskMap.get(url);
        if(downloadTask != null){
          downloadTask.setDownloadListener(listener);
        }
      }

    }

    public void pauseDownload(String url){
      if(downloadTaskMap.containsKey(url)){
        DownloadTask downloadTask = downloadTaskMap.get(url);
        if(downloadTask != null){
          downloadTask.pauseDownload();
        }

        downloadTaskMap.remove(url);

        if(downloadTaskMap.size() > 0){
          getNotificationManager().notify(1, getNotification("正在下載" + downloadTaskMap.size(), -1));
        } else {
          stopForeground(true);
          getNotificationManager().notify(1, getNotification("全部暫停下載", -1));
        }
      }
    }

    public void downloadSuccess(String url){
      if(downloadTaskMap.containsKey(url)){
        DownloadTask downloadTask = downloadTaskMap.get(url);
        downloadTaskMap.remove(url);
        if(downloadTask != null){
          downloadTask = null;
        }

        if(downloadTaskMap.size() > 0){
          getNotificationManager().notify(1, getNotification("正在下載" + downloadTaskMap.size(), -1));
        } else {
          stopForeground(true);
          getNotificationManager().notify(1, getNotification("下載成功", -1));
        }

      }
    }

    public boolean isDownloading(String url){
      if(downloadTaskMap.containsKey(url)){
        return true;
      }

      return false;
    }

    public void cancelDownload(String url){
      if(downloadTaskMap.containsKey(url)){
        DownloadTask downloadTask = downloadTaskMap.get(url);
        if(downloadTask != null){
          downloadTask.cancelDownload();
        }
        downloadTaskMap.remove(url);

        if(downloadTaskMap.size() > 0){
          getNotificationManager().notify(1, getNotification("正在下載" + downloadTaskMap.size(), -1));
        } else {
          stopForeground(true);
          getNotificationManager().notify(1, getNotification("全部取消下載", -1));
        }
      }

      if(url != null){
        String fileName = url.substring(url.lastIndexOf("/"));
        String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
        File file = new File(directory + fileName);

        if(file.exists()){
          file.delete();
          Toast.makeText(DownloadService.this, "Deleted", Toast.LENGTH_SHORT).show();
        }
      }
    }
  }
}

04 源碼

下載地址

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Flutter?web?bridge?通信總結(jié)分析詳解

    Flutter?web?bridge?通信總結(jié)分析詳解

    這篇文章主要為大家介紹了Flutter?web?bridge?通信總結(jié)分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-01-01
  • Android 匿名內(nèi)存深入分析

    Android 匿名內(nèi)存深入分析

    這篇文章主要為大家介紹了Android 匿名內(nèi)存深入分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-03-03
  • 直接拿來用的Android刮獎(jiǎng)控件

    直接拿來用的Android刮獎(jiǎng)控件

    這篇文章主要為大家分享了可以直接拿來用的Android刮獎(jiǎng)控件,非常棒的刮獎(jiǎng)控件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • Flutter實(shí)現(xiàn)紅包動(dòng)畫效果的示例代碼

    Flutter實(shí)現(xiàn)紅包動(dòng)畫效果的示例代碼

    這篇文章主要為大家詳細(xì)介紹了如何利用Flutter實(shí)現(xiàn)紅包的動(dòng)畫效果,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解一下
    2023-06-06
  • android ListView自動(dòng)滾動(dòng)方法

    android ListView自動(dòng)滾動(dòng)方法

    直接在Layout中寫即可,注意下面的stackFromBottom以及transcriptMode這兩個(gè)屬性
    2013-01-01
  • Android中的HOOK技術(shù)是什么

    Android中的HOOK技術(shù)是什么

    最近一段時(shí)間在研究Android加殼和脫殼技術(shù),其中涉及到了一些hook技術(shù),于是將自己學(xué)習(xí)的一些hook技術(shù)進(jìn)行了一下梳理,以便后面回顧和大家學(xué)習(xí)
    2023-02-02
  • FlowLayout流式布局實(shí)現(xiàn)搜索清空歷史記錄

    FlowLayout流式布局實(shí)現(xiàn)搜索清空歷史記錄

    這篇文章主要為大家詳細(xì)介紹了FlowLayout流式布局實(shí)現(xiàn)搜索清空歷史記錄,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-12-12
  • Android實(shí)現(xiàn)漸變啟動(dòng)頁和帶有指示器的引導(dǎo)頁

    Android實(shí)現(xiàn)漸變啟動(dòng)頁和帶有指示器的引導(dǎo)頁

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)漸變啟動(dòng)頁和帶有指示器的引導(dǎo)頁,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-09-09
  • Android多渠道打包配置方案

    Android多渠道打包配置方案

    多渠道打包,顧名思義就是用來區(qū)分同一個(gè)軟件,在不同渠道上的釋放版本,目前我們有需求是要一套軟件代碼庫(kù)多個(gè)項(xiàng)目共同使用,針對(duì)不同的項(xiàng)目打包不同的渠道apk,現(xiàn)學(xué)記錄一下,需要的朋友跟著小編一起來學(xué)習(xí)吧
    2024-06-06
  • Android鬧鐘啟動(dòng)時(shí)間設(shè)置無效問題的解決方法

    Android鬧鐘啟動(dòng)時(shí)間設(shè)置無效問題的解決方法

    這篇文章主要為大家詳細(xì)介紹了Android鬧鐘啟動(dòng)時(shí)間設(shè)置無效問題的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-06-06

最新評(píng)論