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

xe55xuns  于 2022-11-27  发布在  Android
关注(0)|答案(1)|浏览(381)

我试图通过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);

该好名字将显示在通知中心。

ne5o7dgx

ne5o7dgx1#

您应该注册自己,以便在文件下载完成时接收广播。在那里您还可以获取文件名。这需要对代码进行一些修改:
保留从入队调用返回的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));                    
            }
        }
    }
};

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

相关问题