Skip to content

Instantly share code, notes, and snippets.

@SiZapPaaiGwat
Forked from aprock/autoplay.java
Created October 11, 2016 15:49
Show Gist options
  • Save SiZapPaaiGwat/ed52d9cfce74ee3ea9eabed85280b364 to your computer and use it in GitHub Desktop.
Save SiZapPaaiGwat/ed52d9cfce74ee3ea9eabed85280b364 to your computer and use it in GitHub Desktop.
simple trick to autoplay an html5 video element in a webview. (inject javascript to play on load)
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView webview;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
final WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setPluginState(WebSettings.PluginState.ON);
webview.setWebViewClient(new WebViewClient() {
// autoplay when finished loading via javascript injection
public void onPageFinished(WebView view, String url) { webview.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("http://html5demos.com/video");
}
@Override
protected void onPause() {
super.onPause();
webview.onPause();
}
@Override
protected void onResume() {
webview.onResume();
super.onResume();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment