Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

launch mediaplayer on link click in WebView

Tags:

android

I have created an application that loads a website using WebView. Everything works fine except that I'm unable to play any video files within the application. So, what I'm looking for help on is getting my application to launch the mediaplayer when I click on a link ending with .mp4. Any help and tips would be much appreciated!

like image 508
Kyle Avatar asked Aug 01 '10 04:08

Kyle


2 Answers

You need to override the shouldOverrideUrlLoading method of your webViewCient...

final class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.endsWith(".mp4") {
            Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(url));
            view.getContext().startActivity(intent);
            return true;
        } else {
            return super.shouldOverrideUrlLoading(view, url);
        }
    }
}

... that you assign to your webview:

WebViewClient webViewClient = new MyWebViewClient();
webView.setWebViewClient(webViewClient);

Edit: also important that you add:

webView.getSettings().setAllowFileAccess(true);

to allow file downloads/streams such as mp4 files.

like image 98
Mathias Conradt Avatar answered Oct 16 '22 07:10

Mathias Conradt


Note: you may want to also set the data type. This appears to solve some issues in Android 4.0 (Ice Cream Sandwich). For example:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
startActivity(intent);`
like image 34
Chris Avatar answered Oct 16 '22 08:10

Chris