public int copy(InputStream input, RandomAccessFile out)
      throws IOException, NetworkErrorException {

    if (input == null || out == null) {
      return -1;
    }

    byte[] buffer = new byte[BUFFER_SIZE];

    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    if (DEBUG) {
      Log.v(TAG, "length" + out.length());
    }

    int count = 0, n = 0;
    long errorBlockTimePreviousTime = -1, expireTime = 0;

    try {

      out.seek(out.length());

      while (!interrupt) {
        n = in.read(buffer, 0, BUFFER_SIZE);
        if (n == -1) {
          break;
        }
        out.write(buffer, 0, n);
        count += n;

        /*
         * check network
         */
        if (!NetworkUtils.isNetworkAvailable(context)) {
          throw new NetworkErrorException("Network blocked.");
        }

        if (networkSpeed == 0) {
          if (errorBlockTimePreviousTime > 0) {
            expireTime = System.currentTimeMillis() - errorBlockTimePreviousTime;
            if (expireTime > TIME_OUT) {
              throw new ConnectTimeoutException("connection time out.");
            }
          } else {
            errorBlockTimePreviousTime = System.currentTimeMillis();
          }
        } else {
          expireTime = 0;
          errorBlockTimePreviousTime = -1;
        }
      }
    } finally {
      client.close(); // must close client first
      client = null;
      out.close();
      in.close();
      input.close();
    }
    return count;
  }
  public void setData(String url, String speed, String progress, String isPaused) {
    if (hasInited) {
      HashMap<Integer, String> item = getItemDataMap(url, speed, progress, isPaused);

      titleText.setText(NetworkUtils.getFileNameFromUrl(item.get(KEY_URL)));
      speedText.setText(speed);
      if (TextUtils.isEmpty(progress)) {
        progressBar.setProgress(0);
      } else {
        progressBar.setProgress(Integer.parseInt(item.get(KEY_PROGRESS)));
      }
    }
  }
 public void bindTask(DownloadTask task) {
   if (hasInited) {
     titleText.setText(NetworkUtils.getFileNameFromUrl(task.getUrl()));
     speedText.setText(
         task.getDownloadSpeed()
             + "kbps | "
             + task.getDownloadSize()
             + " / "
             + task.getTotalSize());
     progressBar.setProgress((int) task.getDownloadPercent());
     if (task.isInterrupt()) {
       onPause();
     }
   }
 }
 public void setData(HashMap<Integer, String> item) {
   if (hasInited) {
     titleText.setText(NetworkUtils.getFileNameFromUrl(item.get(KEY_URL)));
     speedText.setText(item.get(KEY_SPEED));
     String progress = item.get(KEY_PROGRESS);
     if (TextUtils.isEmpty(progress)) {
       progressBar.setProgress(0);
     } else {
       progressBar.setProgress(Integer.parseInt(progress));
     }
     if (Boolean.parseBoolean(item.get(KEY_IS_PAUSED))) {
       onPause();
     }
   }
 }
  private long download()
      throws NetworkErrorException, IOException, FileAlreadyExistException, NoMemoryException {

    if (DEBUG) {
      Log.v(TAG, "totalSize: " + totalSize);
    }

    /*
     * check net work
     */
    if (!NetworkUtils.isNetworkAvailable(context)) {
      throw new NetworkErrorException("Network blocked.");
    }

    /*
     * check file length
     */
    client = AndroidHttpClient.newInstance("DownloadTask");
    httpGet = new HttpGet(url);
    response = client.execute(httpGet);
    totalSize = response.getEntity().getContentLength();
    if (!(response.getStatusLine().getStatusCode() == 200)) {
      throw new NetworkErrorException("statusCode  is not 200");
    }
    if (file.exists() && totalSize == file.length()) {
      if (DEBUG) {
        Log.v(null, "Output file already exists. Skipping download.");
      }

      throw new FileAlreadyExistException("Output file already exists. Skipping download.");
    } else if (tempFile.exists()) {
      httpGet.addHeader("Range", "bytes=" + tempFile.length() + "-");
      previousFileSize = tempFile.length();

      client.close();
      client = AndroidHttpClient.newInstance("DownloadTask");
      response = client.execute(httpGet);

      if (DEBUG) {
        Log.v(TAG, "File is not complete, download now.");
        Log.v(TAG, "File length:" + tempFile.length() + " totalSize:" + totalSize);
      }
    }

    /*
     * check memory
     */
    long storage = StorageUtils.getAvailableStorage();
    if (DEBUG) {
      Log.i(null, "storage:" + storage + " totalSize:" + totalSize);
    }

    if (totalSize - tempFile.length() > storage) {
      throw new NoMemoryException("SD card no memory.");
    }

    /*
     * start download
     */
    outputStream = new ProgressReportingRandomAccessFile(tempFile, "rw");

    publishProgress(0, (int) totalSize);

    InputStream input = response.getEntity().getContent();
    int bytesCopied = copy(input, outputStream);

    if ((previousFileSize + bytesCopied) != totalSize || totalSize == -1 || interrupt) {
      throw new IOException("Download incomplete: " + bytesCopied + " != " + totalSize);
    }

    if (DEBUG) {
      Log.v(TAG, "Download completed successfully.");
    }

    return bytesCopied;
  }