1111import java .util .HashMap ;
1212import java .util .Map ;
1313import java .util .Scanner ;
14+ import java .util .concurrent .BlockingQueue ;
15+ import java .util .concurrent .LinkedBlockingQueue ;
1416
1517/**
1618 * Created with IntelliJ IDEA.
@@ -26,13 +28,16 @@ public class WebViewJavascriptBridge {
2628 Map <String ,WVJBHandler > _messageHandlers ;
2729 Map <String ,WVJBResponseCallback > _responseCallbacks ;
2830 long _uniqueId ;
31+ BlockingQueue <String > _messageQueue ;
32+
2933 public WebViewJavascriptBridge (Context context ,WebView webview ,WVJBHandler handler ) {
3034 this .mContext =context ;
3135 this .mWebView =webview ;
3236 this ._messageHandler =handler ;
3337 _messageHandlers =new HashMap <String ,WVJBHandler >();
3438 _responseCallbacks =new HashMap <String , WVJBResponseCallback >();
3539 _uniqueId =0 ;
40+ _messageQueue =new LinkedBlockingQueue <String >();
3641 WebSettings webSettings = mWebView .getSettings ();
3742 webSettings .setJavaScriptEnabled (true );
3843 mWebView .addJavascriptInterface (this , "_WebViewJavascriptBridge" );
@@ -71,9 +76,7 @@ public void onPageFinished(WebView webView, String url) {
7176 private class MyWebChromeClient extends WebChromeClient {
7277 @ Override
7378 public boolean onConsoleMessage (ConsoleMessage cm ) {
74- Log .d ("test" , cm .message () + " -- From line "
75- + cm .lineNumber () + " of "
76- + cm .sourceId () );
79+ Log .d ("test" , cm .message ());
7780 return true ;
7881 }
7982
@@ -161,14 +164,36 @@ private void _sendData(String data,WVJBResponseCallback responseCallback,String
161164 if (null !=handlerName ) {
162165 message .put ("handlerName" , handlerName );
163166 }
164- _dispatchMessage (message );
167+ _queueMessage (message );
168+ }
169+
170+ private void _queueMessage (Map <String , String > message ) {
171+ String messageJSON = new JSONObject (message ).toString ();
172+ try {
173+ _messageQueue .put (messageJSON );
174+ _notifyNewMessage ();
175+ } catch (InterruptedException e ) {
176+ Log .e ("test" ,e .getMessage ());
177+ e .printStackTrace ();
178+ }
179+ }
180+
181+ @ JavascriptInterface
182+ public String _getQueuedMessage (){
183+ return _messageQueue .poll ();
184+ }
185+
186+ private void _notifyNewMessage () {
187+ String javascriptCommand =
188+ "javascript:WebViewJavascriptBridge._getNewMessageFromJava();" ;
189+ mWebView .loadUrl (javascriptCommand );
165190 }
166191
167192 private void _dispatchMessage (Map <String , String > message ){
168193 String messageJSON = new JSONObject (message ).toString ();
169194 Log .d ("test" ,"sending:" +messageJSON );
170195 String javascriptCommand =
171- String .format ("javascript:WebViewJavascriptBridge._handleMessageFromOJava ('%s');" ,messageJSON );
196+ String .format ("javascript:WebViewJavascriptBridge._handleMessageFromJava ('%s');" ,messageJSON );
172197 mWebView .loadUrl (javascriptCommand );
173198 }
174199
0 commit comments