Android 使用webview下载文件

Android 使用webview下载文件,android,android-webview,Android,Android Webview,我想用webview下载文件,但只要单击下载链接,应用程序就会自动关闭 mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { Request request = new R

我想用webview下载文件,但只要单击下载链接,应用程序就会自动关闭

mWebView.setDownloadListener(new DownloadListener() {

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

          Request request = new Request( Uri.parse(url)); request.allowScanningByMediaScanner();

          request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

          request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");

          DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

         dm.enqueue(request);

}})

查看日志并告诉我们例外情况。另外,请告诉是哪条语句导致了异常。在我看来,您发布的代码是相同的。是的,此代码不起作用。它与发布的代码是相同的代码。那你为什么发帖?请说明区别。您的应用程序似乎崩溃了,因为您没有实现运行时权限检查器,并且如果要检查并尝试从设置中手动授予权限,请确保添加清单权限,然后尝试下载您正在谈论的权限?DownloadManager不需要任何权限。
public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private String WebUrl = "https://www.google.com";
    String FileName;
    String  URL;
    String Agent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webview);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(WebUrl);

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                FileName = URLUtil.guessFileName(url, contentDisposition, getType(url));
                URL = url;
                Agent = userAgent;
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        startDownload(FileName, URL, Agent);
                    }else {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1001);
                    }
                }else {
                    startDownload(FileName, URL, Agent);
                }
            }
        });
    }

    private void startDownload(String filename, String url, String userAgent) {
        try {
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            String cookie = CookieManager.getInstance().getCookie(url);
            request.setTitle(filename)
                    .setDescription("Downloading")
                    .setMimeType(getType(url))
                    .setAllowedOverMetered(true)
                    .setAllowedOverRoaming(true)
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
            dm.enqueue(request);
            Toast.makeText(this, "Download Started", Toast.LENGTH_SHORT).show();
            FileName = "";
            URL = "";
            Agent = "";

        }catch (Exception e) {
            Toast.makeText(this, "Error Occured : "+e, Toast.LENGTH_SHORT).show();
        }
    }

    private String getType(String link) {
        ContentResolver cr = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        return mimeTypeMap.getExtensionFromMimeType(cr.getType(Uri.parse(link)));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 1001) {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if(!FileName.equals("") && !URL.equals("") && !Agent.equals("")){
                    startDownload(FileName, URL, Agent);
                }
            }
        }
    }
}