/**
   * 停止任务
   *
   * @param url
   * @param remove
   */
  public void stopTask(String url, boolean remove) {
    // 下载中停止task
    removeDownloadingMap(url);

    Iterator<DownloadInfo> downloadingIt = mDownloadingTasks.iterator();
    while (downloadingIt.hasNext()) {
      DownloadInfo b = downloadingIt.next();
      if (TextUtils.equals(b.getUrl(), url)) {
        b.setState(DownloadInfo.PAUSE);
        downloadingIt.remove();
        if (!remove) {
          mPausingTasks.add(b); // 放入暂停队列
        }
        break;
      }
    }

    Iterator<DownloadInfo> waitIt = mWaitTasks.iterator();
    while (waitIt.hasNext()) {
      DownloadInfo b = waitIt.next();
      if (TextUtils.equals(b.getUrl(), url)) {
        b.setState(DownloadInfo.PAUSE);
        waitIt.remove();
        if (!remove) {
          mPausingTasks.add(b); // 放入暂停队列
        }
        break;
      }
    }
  }
 /**
  * 重新下载
  *
  * @param url
  */
 public void restartTask(String url) {
   Iterator<DownloadInfo> pauseIt = mPausingTasks.iterator();
   if (mPausingTasks.size() > 0) {
     synchronized (mIteratorLock) {
       while (pauseIt.hasNext()) {
         DownloadInfo downloadInfo = pauseIt.next();
         if (TextUtils.equals(downloadInfo.getUrl(), url)) {
           if (mDownloadingTasks.size() < MAX_DOWNLOAD_COUNT) {
             downloadInfo.setState(DownloadInfo.DOWNLOADING);
             DownloadHttpTask task =
                 new DownloadHttpTask(downloadInfo, mDownloadUIHandler, mDbHelper, this);
             mDownloadingTaskMap.put(url, task);
             mDownloadingTasks.add(downloadInfo);
             pauseIt.remove();
             task.start();
           } else {
             downloadInfo.setState(DownloadInfo.WAIT);
             mWaitTasks.offer(downloadInfo);
             pauseIt.remove();
           }
           return;
         }
       }
     }
   } else {
     stopTask(url);
     restartTask(url);
   }
 }
 @Override
 public void run() {
   while (!isStop() && !isFinish()) {
     try {
       URL url = new URL(info.getUrl());
       HttpURLConnection con = (HttpURLConnection) url.openConnection();
       String prop = "bytes=" + info.getPos() + "-";
       System.out.println(prop);
       System.out.println(info.getFileSize());
       con.setRequestProperty("RANGE", prop);
       InputStream is = con.getInputStream();
       raf = new RandomAccessFile(info.getFileName(), "rw");
       raf.seek(info.getPos());
       byte[] buffer = new byte[BUFFER_SIZE];
       int b = -1;
       while ((b = is.read(buffer)) != -1 && !isStop()) {
         raf.write(buffer, 0, b);
         info.setPos(info.getPos() + b);
       }
       if (!isStop()) {
         isFinish = true;
       }
     } catch (MalformedURLException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     } finally {
       try {
         raf.close();
       } catch (IOException e) {
       }
     }
   }
 }
Exemple #4
0
 /**
  * Create a builder from the DownloadInfo object.
  *
  * @param downloadInfo DownloadInfo object from which builder fields are populated.
  * @return A builder initialized with fields from downloadInfo object.
  */
 public static Builder fromDownloadInfo(final DownloadInfo downloadInfo) {
   Builder builder = new Builder();
   builder
       .setUrl(downloadInfo.getUrl())
       .setUserAgent(downloadInfo.getUserAgent())
       .setMimeType(downloadInfo.getMimeType())
       .setCookie(downloadInfo.getCookie())
       .setFileName(downloadInfo.getFileName())
       .setDescription(downloadInfo.getDescription())
       .setFilePath(downloadInfo.getFilePath())
       .setReferer(downloadInfo.getReferer())
       .setOriginalUrl(downloadInfo.getOriginalUrl())
       .setContentLength(downloadInfo.getContentLength())
       .setDownloadGuid(downloadInfo.getDownloadGuid())
       .setHasUserGesture(downloadInfo.hasUserGesture())
       .setContentDisposition(downloadInfo.getContentDisposition())
       .setIsGETRequest(downloadInfo.isGETRequest())
       .setPercentCompleted(downloadInfo.getPercentCompleted())
       .setTimeRemainingInMillis(downloadInfo.getTimeRemainingInMillis())
       .setIsResumable(downloadInfo.isResumable())
       .setIsPaused(downloadInfo.isPaused())
       .setIsOffTheRecord(downloadInfo.isOffTheRecord())
       .setIsOfflinePage(downloadInfo.isOfflinePage());
   return builder;
 }
  /**
   * 根据URL获取DownloadInfo
   *
   * @param url
   * @return
   */
  public DownloadInfo getDownloadByUrl(String url) {
    Iterator<DownloadInfo> allTaskIt = mAllTasks.iterator();
    while (allTaskIt.hasNext()) {
      DownloadInfo bean = allTaskIt.next();
      if (TextUtils.equals(bean.getUrl(), url)) {
        return bean;
      }
    }

    return null;
  }
  /** 更改数据,根据指定id更改 */
  public synchronized void update(DownloadInfo info) {
    open();
    ContentValues initialValues = new ContentValues();
    initialValues.put(ID, info.getId());
    initialValues.put(NAME, info.getFilename());
    initialValues.put(LOCAL_NAME, info.getLocalname());
    initialValues.put(URL, info.getUrl());
    initialValues.put(FILE_SIZE, info.getFilesize());
    initialValues.put(COMPLETE_SIZE, info.getCompletesize());

    db.update(DATABASE_TABLE, initialValues, ID + "=" + info.getId(), null);
    close();
  }
 private void executeNextTask() {
   if (mDownloadingTasks.size() < MAX_DOWNLOAD_COUNT) {
     if (mWaitTasks.size() > 0) {
       DownloadInfo downloadInfo = mWaitTasks.poll();
       if (downloadInfo != null) {
         String url = downloadInfo.getUrl();
         downloadInfo.setState(DownloadInfo.DOWNLOADING);
         DownloadHttpTask task =
             new DownloadHttpTask(downloadInfo, mDownloadUIHandler, mDbHelper, this);
         mDownloadingTaskMap.put(url, task);
         task.start();
       }
     }
   } else {
     Logger.d("已达到最大下载数量:" + mDownloadingTasks.size());
   }
 }
 public void start() {
   Log.w(TAG, "start");
   if (downloadInfos != null) {
     if (state == Download_State.Downloading) {
       return;
     }
     state = Download_State.Downloading;
     for (DownloadInfo info : downloadInfos) {
       Log.v(TAG, "startThread");
       new DownloadThread(
               info.getThreadId(),
               info.getStartPos(),
               info.getEndPos(),
               info.getCompeleteSize(),
               info.getUrl())
           .start();
     }
   }
 }
  /**
   * 删除任务
   *
   * @param url
   */
  public void deleteTask(String url) {
    // 从等待队列和下载中
    stopTask(url, true);
    // 从已暂停队列移除
    Iterator<DownloadInfo> pausingIt = mPausingTasks.iterator();
    synchronized (mIteratorLock) {
      while (pausingIt.hasNext()) {
        DownloadInfo bean = pausingIt.next();
        if (TextUtils.equals(bean.getUrl(), url)) {
          bean.setState(DownloadInfo.PAUSE);
          pausingIt.remove();
          break;
        }
      }
    }

    // 从完成队列移除
    Iterator<DownloadInfo> completeIt = mCompleteTasks.iterator();
    synchronized (mIteratorLock) {
      while (completeIt.hasNext()) {
        DownloadInfo bean = completeIt.next();
        if (TextUtils.equals(bean.getUrl(), url)) {
          bean.setState(DownloadInfo.PAUSE);
          completeIt.remove();
          break;
        }
      }
    }

    synchronized (mIteratorLock) {
      String filePath = "";
      // 所有任务
      Iterator<DownloadInfo> allTaskIt = mAllTasks.iterator();
      while (allTaskIt.hasNext()) {
        DownloadInfo bean = allTaskIt.next();
        if (TextUtils.equals(bean.getUrl(), url)) {
          bean.setState(DownloadInfo.PAUSE);
          filePath = bean.getTargetPath();
          allTaskIt.remove();
          break;
        }
      }

      if (!StringUtils.isEmpty(filePath)) {
        FileUtils.deleteFile(filePath);
      }
    }

    synchronized (mIteratorLock) {
      // 任务时间回调
      for (Map.Entry<String, List<DownloadListener>> entry : mListenerListMap.entrySet()) {
        List<DownloadListener> listenerList = entry.getValue();
        if (listenerList != null) {
          listenerList.clear();
          listenerList = null;
        }
      }
    }

    // 清除数据库
    try {
      mDbHelper.delete(DownloadInfo.class, WhereBuilder.b("url", "=", url));
    } catch (DbException e) {
      Logger.e(e);
    }
  }