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; }