How can I download the file by using webview? (this case is weird)

前端 未结 2 1763
夕颜
夕颜 2021-01-02 10:03

I want to download the file (such as .mp3) from the website by using webview but the problem is Whenever I tap on the link, it will open the browser (Default one) Which is a

相关标签:
2条回答
  • 2021-01-02 10:13

    Implement a WebViewClient to use with your WebView. In it, override the shouldOverrideUrlLoading method, where you should check if it's an mp3 file, and then pass that URL to the DownloadManager or whatever you're using to actually download the file. Here's a rough idea:

        // This will handle downloading. It requires Gingerbread, though
        final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    
        // This is where downloaded files will be written, using the package name isn't required
        // but it's a good way to communicate who owns the directory
        final File destinationDir = new File (Environment.getExternalStorageDirectory(), getPackageName());
        if (!destinationDir.exists()) {
            destinationDir.mkdir(); // Don't forget to make the directory if it's not there
        }
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading (WebView view, String url) {
                boolean shouldOverride = false;
                // We only want to handle requests for mp3 files, everything else the webview
                // can handle normally
                if (url.endsWith(".mp3")) {
                    shouldOverride = true;
                    Uri source = Uri.parse(url);
    
                    // Make a new request pointing to the mp3 url
                    DownloadManager.Request request = new DownloadManager.Request(source);
                    // Use the same file name for the destination
                    File destinationFile = new File (destinationDir, source.getLastPathSegment());
                    request.setDestinationUri(Uri.fromFile(destinationFile));
                    // Add it to the manager
                    manager.enqueue(request);
                }
                return shouldOverride;
            }
        });
    
    0 讨论(0)
  • 2021-01-02 10:30
    if(mWebview.getUrl().contains(".mp3") {
     Request request = new Request(
                            Uri.parse(url));
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download"); 
    // You can change the name of the downloads, by changing "download" to everything you want, such as the mWebview title...
                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                    dm.enqueue(request);        
    
        }
    
    0 讨论(0)
提交回复
热议问题