如何使用Android DownloadManager? [英] How to use Android DownloadManager?
问题描述
我想使用Android DownloadManager类将文件下载到SDCard:
请求请求=新请求(Uri.parse( URL));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename); // set destination dir
long downloadId = downloader.enqueue(request);但是我总是得到下载状态= 16(STATUS_FAILED),并且原因= 1008(ERROR_CANNOT_RESUME),
我已经在清单中包含了android.permission.WRITE_EXTERNAL_STORAGE。
当我注释出
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename);
并使用默认的下载文件夹,没关系。但是我不知道文件在哪里,我从结果中得到的地方就是这样:
content:/ / download / my_downloads / 95
我不知道如何将文件复制到SDCard。 p>
我想要的是将文件下载到SDCard 。有人可以帮忙吗?谢谢!
您可以从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 = 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;
}
I want to download a file to SDCard with Android DownloadManager class:
Request request = new Request(Uri.parse(url));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); //set destination dir
long downloadId = downloader.enqueue(request);
But I always get download status=16(STATUS_FAILED), and reason=1008(ERROR_CANNOT_RESUME). I have already included android.permission.WRITE_EXTERNAL_STORAGE in the manifest.
When i commented out the
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
and use the default download folder, it's OK. But I don't know where is the file goes, the localUri I get from the result is something like:
content://downloads/my_downloads/95
I don't know how to copy the file to SDCard.
What I want is download a file to SDCard. Could someone help? Thanks!
You can retrieve file path from localUri like this:
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;
}
这篇关于如何使用Android DownloadManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!