@Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_INIT: // 获得初始化的结果 FileInfo fileInfo = (FileInfo) msg.obj; Log.i("fileTest", fileInfo.toString()); // 启动下载任务 DownloadTask task = new DownloadTask(DownloadService.this, fileInfo, 3); task.download(); // 把下载任务加入 到下载任务集合 mTasks.put(fileInfo.getId(), task); break; } }
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (ACTION_START.equals(intent.getAction())) { FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo"); Log.i("fileInfo", "start:" + fileInfo.toString()); // 启动初始化线程 DownloadTask.sExecutorService.execute(new InitThread(fileInfo)); } else if (ACTION_PAUSE.equals(intent.getAction())) { FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo"); Log.i("fileInfo", "pause:" + fileInfo.toString()); // 从任务集合获得任务 DownloadTask task = mTasks.get(fileInfo.getId()); // 暂停下载 if (task != null) { task.isPause = true; } } return super.onStartCommand(intent, flags, startId); }
@Override public void run() { HttpURLConnection conn = null; RandomAccessFile raf = null; try { URL url = new URL(fileInfo.getFileUrl()); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); int length = -1; if (conn.getResponseCode() == HttpStatus.SC_OK) { length = conn.getContentLength(); } if (length < 0) { return; } File dir = new File(DOWNLOAD_DIR); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, fileInfo.getFilename()); raf = new RandomAccessFile(file, "rwd"); raf.setLength(length); fileInfo.setLength(length); mHandler.obtainMessage(MSG_INIT, fileInfo).sendToTarget(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (conn != null) { conn.disconnect(); } if (raf != null) { raf.close(); } } catch (IOException e) { e.printStackTrace(); } } }