Playing an MP4 or MP3 from a Link within an Android WebView

11,614

Ok - found the answer after much searching on different topics.

The answer lies in intercepting the link as such:

     public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.endsWith(".mp3")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse(url), "audio/*");
            view.getContext().startActivity(intent);   
            return true;
        } else if (url.endsWith(".mp4") || url.endsWith(".3gp")) {
                Intent intent = new Intent(Intent.ACTION_VIEW); 
                intent.setDataAndType(Uri.parse(url), "video/*");
                view.getContext().startActivity(intent);   
                return true;
        } else {
            return super.shouldOverrideUrlLoading(view, url);
        }
     }
Share:
11,614
Robbe
Author by

Robbe

Updated on June 04, 2022

Comments

  • Robbe
    Robbe almost 2 years

    I have searched far and wide and can't seem to find the exact answer or even close.

    I have a WebView that opens a webpage (JQuery Mobile) and all is well.

    Within that page there are static links to both mp3 and mp4 files. The idea is that when clicked - the device will open the default sound or movie app to play each. This works when using the Android browser without issue.

    When I open inside WebView, and click the same links - nothing happens. Nothing opens, or plays.

    I'm setting getSettings as wide open as I can.

    **web.getSettings().setJavaScriptEnabled(true); 
        web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        web.getSettings().setPluginsEnabled(true);
        web.getSettings().setSupportMultipleWindows(true);
        web.getSettings().setSupportZoom(true);
        web.getSettings().setBuiltInZoomControls(true);
        web.getSettings().setAllowFileAccess(true);
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);**
    

    I'll also note that I believe "shouldOverrideUrlLoading" only works on the initial URL loaded in the WebView. This is a link inside that WebView - so does not seem to work.

    I had tried that.

    Any ideas on how to enable the user the ability to click a link within a WebView and open the associate application as the browser does?

    Much Appreciated!

    /r