老熟女激烈的高潮_日韩一级黄色录像_亚洲1区2区3区视频_精品少妇一区二区三区在线播放_国产欧美日产久久_午夜福利精品导航凹凸

重慶分公司,新征程啟航

為企業提供網站建設、域名注冊、服務器等服務

android中的多線程下載怎么利用AsyncTask實現

android中的多線程下載怎么利用AsyncTask實現?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

創新互聯主營龍口網站建設的網絡公司,主營網站建設方案,APP應用開發,龍口h5微信小程序開發搭建,龍口網站營銷推廣歡迎龍口等地區企業咨詢

01 效果圖

android中的多線程下載怎么利用AsyncTask實現

02 核心類 - DownloadTask.class

public class DownloadTask extends AsyncTask {
  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 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();
        }
      }
    }
  }
}

關于android中的多線程下載怎么利用AsyncTask實現問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創新互聯行業資訊頻道了解更多相關知識。


網站欄目:android中的多線程下載怎么利用AsyncTask實現
URL地址:http://www.xueling.net.cn/article/jgcgde.html

其他資訊

在線咨詢
服務熱線
服務熱線:028-86922220
TOP
主站蜘蛛池模板: 中文字幕免费专区 | 丰满人妻一区二区三区视频53 | 国产午夜毛片 | 国产中文字幕第一页 | 野花香日本在线观看免费视频 | 蜜臀av一区二区三区 | 99久久精品国产免费看 | 亚洲日韩欧美一区久久久久我 | 亚洲国产欧美日韩欧美特级 | 亚洲精品久久婷婷丁香51 | 成人涩涩涩视频在线观看 | av毛片| 成年精品 | 尹人香蕉久久99天天拍久女久 | 国产精品国产一区 | 老司机免费福利在线观看 | 浮生影视在线观看免费高清 | 日本伦理按摩 | 高清人妻喷潮AV综合网 | 色五月婷婷成人网 | av在线免费看不卡 | 44444kk在线观看三免费 | 人妻系列无码专区无码中出 | 潜行者40集连续剧免费观看 | 亚洲欧美日韩国产精品 | 欧美性战a久久久久久 | 亚洲a一区二区 | 欧美区精品系列在线观看不卡 | 国内嫩模私拍精品视频 | 人妻系列综合第一页 | 91亚洲人成网污www | 国产精品不卡在线观看 | 欧美激情在线一区二区 | 91情趣视频 | 717影院理论午夜伦八戒 | 日本边添边摸边做边爱的网站 | 三级中文字幕永久在线 | 欧美又大又色又爽bbbbb片 | 亚洲成人123 | 欧美性猛交xxxx免费看野外 | 成人性生交天码免费看 |