How to Play a Video in a Webview with Android

Android: playing youtube video on Webview

try this

String frameVideo = "<html><body>Video From YouTube<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

WebView displayYoutubeVideo = (WebView) findViewById(R.id.mWebView);
displayYoutubeVideo.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings webSettings = displayYoutubeVideo.getSettings();
webSettings.setJavaScriptEnabled(true);
displayYoutubeVideo.loadData(frameVideo, "text/html", "utf-8");

also set in manifist file android:hardwareAccelerated="true"

<application
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

</application>

How to Allow Webview Accessing Online Video Using Android Video Player Application?

One way is to intercept the HTTP request from the Webview. refer to this

Then check if the request URL is a video url. if yes, open the url using Intent

Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.parse(videoPath), "video/mp4");
startActivity(intent);

Edit:
Below is my working example, when you click on a link that ends with "mp4", android will open the url with default media players.

    webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
println("shouldOverrideUrlLoading")
println(request?.url.toString())
val url :String = request?.url.toString()
if (url.endsWith("mp4")) {
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(Uri.parse(url), "video/mp4")
startActivity(intent)
return true
}
return false
}
}
val videoPath = "http://techslides.com/sample-webm-ogg-and-mp4-video-files-for-html5"
webView.loadUrl(videoPath)

Manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ecl.webtest">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>


Related Topics



Leave a reply



Submit