Android下载文件通过DownloadManager无法正常工作

时间:2013-03-08 10:39:15

标签: android download download-manager

我正在尝试通过DownloadManager下载文件,它可以在大多数手机(Nexus系列,S3等)上完美运行但在Galaxy S2上出于某种原因下载有效,但文件名设置错误,当我尝试打开它时(无论是来自通知,还是下载应用程序)它都说无法打开文件,即使对于像jpeg,gif,png等文件也是如此。

enter image description here

以下是代码:

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);

通知中心会显示好名称。

1 个答案:

答案 0 :(得分:0)

您应该在文件下载完成后注册自己接收广播。在那里你也可以获取文件名。这需要对代码进行一些更改:

保留从enqueue call返回的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));                    
            }
        }
    }
};

假设下载文件名不是好习惯。如果你再次下载它而不删除前一个,它将自动获得后缀。