我想使用Android DownloadManager类将文件下载到SDCard:
Request request = new Request(Uri.parse(url));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); //set destination dir
long downloadId = downloader.enqueue(request);
但我总是得到下载状态= 16(STATUS_FAILED),并且reason = 1008(ERROR_CANNOT_RESUME)。我已经在清单中包含了android.permission.WRITE_EXTERNAL_STORAGE。
当我评论
时request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
并使用默认的下载文件夹,没关系。但是我不知道文件在哪里,我从结果得到的localUri就像是:
content://downloads/my_downloads/95
我不知道如何将文件复制到SD卡。
我想要的是将文件下载到 SDCard 。有人可以帮忙吗?谢谢!
答案 0 :(得分:17)
您可以从localUri检索文件路径,如下所示:
public static String getFilePathFromUri(Context c, Uri uri) {
String filePath = null;
if ("content".equals(uri.getScheme())) {
String[] filePathColumn = { MediaColumns.DATA };
ContentResolver contentResolver = c.getContentResolver();
Cursor cursor = contentResolver.query(uri, filePathColumn, null,
null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
} else if ("file".equals(uri.getScheme())) {
filePath = new File(uri.getPath()).getAbsolutePath();
}
return filePath;
}
答案 1 :(得分:13)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
给了我/mnt/sdcard/downloads
我可以在onReceive (ACTION_DOWNLOAD_COMPLETE)
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(downloadId);
Cursor cur = dm.query(query);
if (cur.moveToFirst()) {
int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == cur.getInt(columnIndex)) {
String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
File mFile = new File(Uri.parse(uriString).getPath());
....
} else {
Toast.makeText(c, R.string.fail, Toast.LENGTH_SHORT).show();
}
}