全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

android使用AsyncTask实现多线程下载实例

AsyncTask不仅方便我们在子线程中对UI进行更新操作,还可以借助其本身的线程池来实现多线程任务。下面是一个使用AsyncTask来实现的多线程下载例子。

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 源码

下载地址

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# android  # AsyncTask  # 多线程下载  # asynctask多线程  # Android 使用AsyncTask实现多任务多线程断点续传下载  # Android多线程AsyncTask详解  # Android使用AsyncTask实现多线程下载的方法  # Android开发笔记之:深入理解多线程AsyncTask  # Android 使用AsyncTask实现断点续传  # Android 使用AsyncTask实现多线程断点续传  # 来实现  # 多线程  # 是一个  # 还可以  # 下载地址  # 中对  # 大家多多  # getPath  # exists  # DIRECTORY_DOWNLOADS  # Environment  # getExternalStoragePublicDirectory  # OkHttpClient  # return  # getContentLength  # length  # contentLength  # downloadLength  # downloadUrl  # long 


相关文章: 如何在阿里云完成域名注册与建站?  高防服务器:AI智能防御DDoS攻击与数据安全保障  制作表格网站有哪些,线上表格怎么弄?  ,有什么在线背英语单词效率比较高的网站?  如何用免费手机建站系统零基础打造专业网站?  焦点电影公司作品,电影焦点结局是什么?  如何配置支付宝与微信支付功能?  猪八戒网站制作视频,开发一个猪八戒网站,大约需要多少?或者自己请程序员,需要什么程序员,多少程序员能完成?  最好的网站制作公司,网购哪个网站口碑最好,推荐几个?谢谢?  太原网站制作公司有哪些,网约车营运证查询官网?  实惠建站价格推荐:2025年高性价比自助建站套餐解析  巅云智能建站系统:可视化拖拽+多端适配+免费模板一键生成  建站主机选择指南:服务器配置与SEO优化实战技巧  香港服务器租用费用高吗?如何避免常见误区?  大同网页,大同瑞慈医院官网?  如何快速搭建响应式可视化网站?  公司网站制作费用多少,为公司建立一个网站需要哪些费用?  电影网站制作价格表,那些提供免费电影的网站,他们是怎么盈利的?  阿里云网站搭建费用解析:服务器价格与建站成本优化指南  武汉网站如何制作,黄黄高铁武穴北站途经哪些村庄?  网页设计与网站制作内容,怎样注册网站?  建站DNS解析失败?如何正确配置域名服务器?  零基础网站服务器架设实战:轻量应用与域名解析配置指南  专业企业网站设计制作公司,如何理解商贸企业的统一配送和分销网络建设?  视频网站制作教程,怎么样制作优酷网的小视频?  如何通过IIS搭建网站并配置访问权限?  金*站制作公司有哪些,金华教育集团官网?  官网网站制作腾讯审核要多久,联想路由器newifi官网  Python多线程使用规范_线程安全解析【教程】  如何将凡科建站内容保存为本地文件?  专业商城网站制作公司有哪些,pi商城官网是哪个?  c++怎么使用类型萃取type_traits_c++ 模板元编程类型判断【方法】  建站之星ASP如何实现CMS高效搭建与安全管理?  网站制作网站,深圳做网站哪家比较好?  网站插件制作软件免费下载,网页视频怎么下到本地插件?  b2c电商网站制作流程,b2c水平综合的电商平台?  建站主机是否等同于虚拟主机?  如何制作一个表白网站视频,关于勇敢表白的小标题?  网站图片在线制作软件,怎么在图片上做链接?  网站设计制作公司地址,网站建设比较好的公司都有哪些?  如何在橙子建站中快速调整背景颜色?  php条件判断怎么写_ifelse和switchcase的使用区别【对比】  如何快速打造个性化非模板自助建站?  css网站制作参考文献有哪些,易聊怎么注册?  如何通过网站建站时间优化SEO与用户体验?  如何在阿里云虚拟服务器快速搭建网站?  如何确保FTP站点访问权限与数据传输安全?  免费制作统计图的网站有哪些,如何看待现如今年轻人买房难的情况?  如何在Windows环境下新建FTP站点并设置权限?  宝华建站服务条款解析:五站合一功能与SEO优化设置指南 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。