http://blog.csdn.net/carson_ho/article/details/64904691
Pass
WebViewClient
The method
shouldOverrideUrlLoading ()
Callback Intercept URL
<! DOCTYPE html><Html><Head><Metacharset="Utf-8" ><Title>carson_ho</Title><Script> functionCallandroid(){/* The agreed URL protocol is: js://webview?arg1=111&arg2=222*/document.location = "js://webview?arg1=111&arg2=222";} </script></ head><!--click the button to invoke the Callandroid () method-- <body> < button type= "button" id=" button1 "onclick= "callandroid ()" > Click Call android Code </ button> </body></HTML>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
When the JS is loaded by Android mWebView.loadUrl("file:///android_asset/javascript.html")
, it will be recalled shouldOverrideUrlLoading ()
, then continue to see Step 2:
Step 2: Replicate on Android via WebviewclientshouldOverrideUrlLoading ()
Mainactivity.java
PublicClassMainactivityExtendsappcompatactivity {WebView Mwebview;Button button;@OverrideProtectedvoidOnCreate (Bundle savedinstancestate) {Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mwebview = (WebView) Findviewbyid (R.id.webview); WebSettings websettings = Mwebview.getsettings ();Set permissions to interact with JS Websettings.setjavascriptenabled (true);Set Allow JS pop-up window websettings.setjavascriptcanopenwindowsautomatically (true);Step 1: Load the JS codeThe format is: file:///android_asset/file name. html Mwebview.loadurl ("File:///android_asset/javascript.html");The Shouldoverrideurlloading method of the Webviewclient class of replication mwebview.setwebviewclient (New Webviewclient () {@OverridePublicBooleanShouldoverrideurlloading (WebView view, String URL) {Step 2: Determine if the URL is required according to the parameters of the ProtocolGenerally judged by scheme (protocol format) & Authority (protocol name) (first two parameters)Assume that the incoming URL = "js://webview?arg1=111&arg2=222" (also a well-agreed-upon) URI uri = uri.parse (URL);If the protocol of the URL = pre-agreed JS protocolParse the argument downif (Uri.getscheme () equals ("JS")) { //if authority = WebView in the pre-agreed agreement, that is, the protocol that represents the agreed protocol //So intercept the URL, the following JS begins to call an The droid needs the method if (Uri.getauthority (). Equals ("WebView")) { //Step 3:// The logical System.out.println to be invoked to execute JS ( "JS calls the Android method"); //can have parameters on the protocol and pass to Android on hashmap<string, string> params = new hashmap<> (); Set<string> collection = Uri.getqueryparameternames (); } return true; return super.shouldoverrideurlloading (view, URL);}} ); } }
Android App JS