Android Synchronous Javascript with WebView on Lollipop -


Using the borrowed technology, we have successfully implemented many features within our app that can synchronize our Android app with data Gives permission to receive A webview.

Here is an example from GarterBurling:

  Import java.util.concurrent.CountDownLatch; Import java.util.concurrent.TimeUnit; Import android.content.Context; Import android.util.log; Import android.webkit.WebView; / ** * Synchronous JavaScript provides an interface for receiving calls * @author btate * * / public class SynchronousJavascriptInterface {/ ** tagging for logging * / personal static final string TAG = "Synchronous JavaScript Interface"; / ** Name of the JavaScript interface to add to the web view. * / Private Final String InterfaceName = "SinkJS"; / ** Used for waiting for the countdown latch result. * / Private countdown to Latch = Null; Return the wait value for ** * / Private string return value; / ** * Base Constructor * / Public Synchronous JavaScript Interface () {} / ** * Evaluates expression and returns value. * @Verified Webview * @PRAM Expression * @Ruran * / Public String getJSValue (Webview Webview, String Expression) {Latch = New CountdownLock (1); String code = "javascript: window." + InterfaceName + ".setValue ((function () {try {return" + expression + "+ \" \ ";} hold (js_eval_err) {return '}}}}) ());"; WebView.loadUrl (code); Try {// Set 1 second timeout, if there is an error latch. Waiting (1, Time Unit. SENDS); Return return value; } Grip (interrupted ejection e) {log. A (tag, "interrupted", e); } Return tap; } / ** * Receives value from Javascript. * @ Ultimate Value * / Public Zero Set Value (String Value) {returnValue = value; Try {latch.countDown (); } Hold (exception e) {}} / ** * get the name of the name @return * / public String getInterfaceName () {return this.interfaceName; }}  

This JS interface is used like this:

  Webview webview = new webview (reference); Synchronous Javascript interface jsInterface = new jsInterface (); WebView.addJavascriptInterface (jsInterface, jsInterface.getInterfaceName ()); String jsResult = jsInterface.getJSValue (webview, "2 + 5");  

Despite working well on Android 4.0 - 4.4.4 It is not working for us with Android 5.0 (Lollipop).

It appears that in the lollipop JS is implemented, after the latch countdown is completed, while first it will return a value before completing the countdown.

Has something changed with threads that is executed on JS in WebWeb? And is there no way that I can fix it without having to re-write the bigger sections of my app which is able to call JS synchronization?

  loadUrl ("javascript:" + code)  
Do not work with P> API> 19, instead use:

  evaluate javascript (code, blank);  

Or, you can improve your code to use the provided callback by evaluating JavaScript.


Comments