处理WebView文件下载和运行时权限

Rom*_*naV 10 android download webview

当我点击其中的一个按钮时WebView,它应该下载一个PDF文件,该文件将保存到外部存储器中.

为此,我设置了一个DownloadListener:

webview.setDownloadListener(new DownloadHandler());

public class DownloadHandler implements 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.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, getFileName(url));
        DownloadManager dm = (DownloadManager)getContext().getSystemService(getContext().DOWNLOAD_SERVICE);
        dm.enqueue(request);
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试在Android M上执行此操作时会出现问题,在运行时会询问所有权限.

在启动下载之前,我应该如何首先请求许可,并且根据是否授予下载继续或不继续下载?

下载URL shouldInterceptRequest没有调用shouldOverrideUrlLoading,所以我甚至不确定如何取消先检查权限的请求.

一旦WebView启动不是一个选项,请求权限,因为你可以做的不仅仅是下载文件.