private void saveImage(int index) { String dest = AcApp.getPreferenceImageSaveDir(); String path = mList.get(index); Uri uri = Uri.parse(path); File saveFile; if (uri.getScheme().equals("http")) { // FIXME: volley 的缓存任务还没有被执行的时候是会获取不到数据的 byte[] diskCache = AcApp.getDataInDiskCache(path); if (diskCache != null) { saveFile = new File(dest + "/" + FileUtil.getHashName(path)); if (!FileUtil.save(diskCache, saveFile.getAbsolutePath())) { saveFile = null; } } else { File cache = FileUtil.generateImageCacheFile(path); saveFile = FileUtil.copy(cache, dest); } } else { File cache = new File(uri.getPath()); saveFile = FileUtil.copy(cache, dest); } if (saveFile != null && saveFile.exists()) { MobclickAgent.onEvent(this, "save_pic"); Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(saveFile)); sendBroadcast(intent); AcApp.showToast(getString(R.string.save_success) + ":" + saveFile.getAbsolutePath()); } else AcApp.showToast(getString(R.string.save_failed)); }
@Override protected String doInBackground(Uri... params) { loading = true; Uri uri = params[0]; if (uri == null || mUri.getHost() == null) return null; File cache = FileUtil.generateImageCacheFile(uri.toString()); if (cache.exists() && cache.canRead()) { return cache.getAbsolutePath(); } else { cache.getParentFile().mkdirs(); } File temp = new File(cache.getAbsolutePath() + ".tmp"); InputStream in = null; OutputStream out = null; try { URL parsedUrl = new URL(uri.toString()); for (int i = 0; i < 3 && !isCancelled(); i++) { HttpURLConnection connection = Connectivity.openDefaultConnection(parsedUrl, 3000 + i * 1500, (3000 * (2 + i))); if (temp.exists()) { connection.addRequestProperty("Range", "bytes=" + temp.length() + "-"); out = new FileOutputStream(temp, true); } else out = new FileOutputStream(temp); try { int responseCode = connection.getResponseCode(); if (responseCode == 200 || responseCode == 206) { in = connection.getInputStream(); FileUtil.copyStream(in, out); cache.delete(); if (!temp.renameTo(cache)) { Log.w(TAG, "重命名失败" + temp.getName()); } return cache.getAbsolutePath(); } } catch (SocketTimeoutException e) { Log.w(TAG, "retry", e); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.close(in); IOUtils.close(out); } return null; }