3

我正在尝试通过 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);

好名字显示在通知中心。

4

1 回答 1

0

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

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

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

于 2013-03-08T11:16:23.990 回答