Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Identify whether Web-view playing sound or not

the web page loading inside webview is auto playing in background, i would like to detect when sound stops and than display toast message.

thanks

like image 279
Fou Avatar asked May 09 '15 03:05

Fou


1 Answers

That's can be easily if you use the JavascriptInterface. Follow my step:

1.Create a interface callback:

public class MediaWebInterface {

    public MediaWebInterface() {

    }

    @JavascriptInterface
    public void setEndedIndex(int pIndex) {
        // Call when the audio ended.
    }

}

2.Create a javascript that contain an "ended" listener:

<script type='text/javascript'>window.onload=function(){var n=document.getElementsByTagName("audio"),r=n.length;for(var o=0;o<r;o++)n[o].setAttribute("index",o),n[o].addEventListener("ended",function(){for(var e=0;e<r;e++)this===n[e]&&window.external.setEndedIndex(e)})}
</script>

3.Load the html data into a String and append above javascript to you html data String:

// Enable javascript support
mWebView.getSettings().setJavaScriptEnabled(true); 
mWebView.addJavascriptInterface(new MediaWebInterface(mHandler), "external");
mWebView.loadDataWithBaseURL(mBaseURL, mHTMLData+aboveJavascript, null, "utf-8", null);

4.When the audio stop, and it will call the MediaWebInterface.setEndedIndex(pIndex), and pIndex is the index of the audio.

Hava fun, and try it!

Please read the WebView.addJavascriptInterface() first!

Warnning: If you use proguard, you should add follow script into your proguard-project.txt. Otherwise, the callback will invalid. Because the class name and method will obfuscate, so the javascript can't callback.

//Preserved javaScript interface class
-keepclassmembers class com.xxx.xxx.javascript.MediaWebInterface {
   public *;
}
like image 65
codezjx Avatar answered Sep 27 '22 00:09

codezjx