我正在尝试通过DownloadManager下载文件,它在大多数手机(Nexus系列,S3等)上都能很好地工作,但在Galaxy S2上,由于某种原因,下载可以工作,但文件的名称设置错误,当我试图打开它(无论是从通知,或下载应用程序),它显示该文件无法打开,即使是对于像jpeg,gif,png等文件。
代码如下:
DownloadManager downloadManager = (DownloadManager) service
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request downloadReq = new DownloadManager.Request(
Uri.parse(URL));
downloadReq
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE);
downloadReq.allowScanningByMediaScanner();
downloadReq.setMimeType(attachment.mimeType);
downloadReq.setTitle(attachment.fileName);
downloadReq.setDescription("attachment");
downloadReq.setDestinationInExternalFilesDir(service,
Environment.DIRECTORY_DOWNLOADS, "");
downloadReq
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE
| DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadIDs.add(downloadManager.enqueue(downloadReq));
另外请注意,所有的网址都是https,而手机的android版本是4.1.2,你知道吗?
非常感谢!
更新:如果我在此调用中添加文件名:
downloadReq.setDestinationInExternalFilesDir(service,
Environment.DIRECTORY_DOWNLOADS, attachment.fileName);
好的名字会显示在通知中心。
发布于 2013-03-08 19:16:24
您应该进行注册,以便在文件下载完成时接收广播。在那里,您还可以获取文件名。这将需要对代码进行一些更改:
保留入队呼叫返回的ID:
long enqueue = downloadManager.enqueue(downloadReq);
注册接收器以获取广播:
getApplicationContext().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
声明接收者:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
return;
}
context.getApplicationContext().unregisterReceiver(receiver);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Log.i(TAG, "downloaded file " + uriString);
} else {
Log.i(TAG, "download failed " + c.getInt(columnIndex));
}
}
}
};
假设文件名用于下载不是一个好的做法。如果你在没有删除前一个的情况下再次下载它,它将自动获得一个后缀。
https://stackoverflow.com/questions/15292063
复制相似问题