开发者

launch mediaplayer on link click in WebView

开发者 https://www.devze.com 2023-01-09 22:56 出处:网络
I have created an applic开发者_JS百科ation 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 h

I have created an applic开发者_JS百科ation 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!


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.


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);`
0

精彩评论

暂无评论...
验证码 换一张
取 消