Android:在 webview 中下载在 oreo 中不起作用,它在 Oreo 设备中强制关闭

Android: Downloading in webview not working in oreo, it force closes in Oreo devices

下载管理器代码在 Android WebView 中不适用于 Oreo 设备,但它适用于旧版本 如果不是 Oreo 设备,它会烤 "downloading file" 并下载,但如果是 Oreo,它会强制关闭(崩溃)

下面是我正在使用的代码(片段)

 webView.setDownloadListener(new DownloadListener() {
        @Override

        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {

            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!

            DownloadManager dm = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getActivity().getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
                    Toast.LENGTH_LONG).show();
        }
    });

尝试通过移除

来移除字体预加载
<meta-data 
android:name="preloaded_fonts" 
android:resource="@array/preloaded_fonts" />  

来源

这是我想出来并为我工作的代码。

注意:代码是在一个片段中执行的,对于 main activity remove getActivity(). 在清单中给予许可

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Tutorial 权限提示

代码:

webView.setDownloadListener(new DownloadListener() {

        @Override

        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));
            if(Build.VERSION.SDK_INT <= 26 ){
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
            }
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!

            DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getActivity().getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
                    Toast.LENGTH_LONG).show();


        }



    });