首页 > 解决方案 > 我无法在 Android 10 中使用 DownloadManger 下载文件?

问题描述

最近我将我的应用程序更新到Android 10 / API 29现在,我无法使用 android 默认下载管理器下载图像文件并显示以下错误。

>>>>>: java.lang.SecurityException: Unsupported path /storage/emulated/0/MyFolder/RPS_20200930_191705.png

我的代码

 private boolean downloadTask(String url) throws Exception {
        if (!url.startsWith("http")) {
            return false;
        }
        String name = new SimpleDateFormat("'RPS_'yyyyMMdd_HHmmss'.png'", Locale.ENGLISH).format(new Date());
        try {
            File file = new File(Environment.getExternalStorageDirectory(), "MyFolder");
            if (!file.exists()) {
                //noinspection ResultOfMethodCallIgnored
                file.mkdirs();
            }
            File result = new File(file.getAbsolutePath() + File.separator + name);
            DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); 
            request.setDestinationUri(Uri.fromFile(result)); 
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            if (downloadManager != null) {
                downloadManager.enqueue(request);
            }
            mToast(mContext, "Starting download...");
            MediaScannerConnection.scanFile(WebActivity.this, new String[]{result.toString()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                        }
                    });
        } catch (Exception e) {
            Log.e(">>>>>", e.toString());
            mToast(this, e.toString());
            return false;
        } 
        return true;
    }

甚至我还添加了读/写权限和 LegacyExternalStorag manifiest.xml

android:requestLegacyExternalStorage="true"

和使用

downloadTask("https://linkpicture.com/Images/gplogo.png");

标签: androidpathandroid-download-manager

解决方案


推荐阅读