Android can use WebView to load Web pages, while Java code on the Android side can be called with JavaScript code on the Web page.
:
(i) Android part:
Layout code:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:focus Able= "true" android:focusableintouchmode= "true" android:orientation= "vertical" android:padding= "8DP" Tools:con Text= ". Mainactivity "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_conten T "> <edittext android:id=" @+id/input_et "android:layout_width=" 0DP "Android: layout_height= "Wrap_content" android:singleline= "true" android:layout_weight= "1" android: Hint= "Please enter information"/> <button android:text= "java call js" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:onclick= "Sendinfotojs"/> </LinearLayout> & Lt WebView android:id= "@+id/webviEW "android:layout_width=" match_parent "android:layout_height=" Match_parent "/></linearlayout>
Activity code:
/** * Android WebView interacts with Javascript. */public class Mainactivity extends Actionbaractivity {private WebView WebView; @SuppressLint ({"setjavascriptenabled", "Addjavascriptinterface"}) @Override protected void OnCreate (Bundle savedinst Ancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); WebView = (WebView) Findviewbyid (R.id.webview); Webview.setverticalscrollbaroverlay (TRUE); Set WebView support for JavaScript webview.getsettings (). Setjavascriptenabled (True); String url = "http://192.168.1.27/js_17_android_webview.html"; Webview.loadurl (URL); In JS, call the native Java method Webview.addjavascriptinterface (new Jsinterface (This), "Androidwebview"); Add Client Support Webview.setwebchromeclient (new Webchromeclient ()); } private class Jsinterface {private Context mcontext; Public Jsinterface (Context context) {This.mcontext = context; }//Call Wind in JSow. ANDROIDWEBVIEW.SHOWINFOFROMJS (name), this method is triggered. @JavascriptInterface public void Showinfofromjs (String name) {toast.maketext (Mcontext, name, Toast.leng Th_short). Show (); }}//In Java call JS code public void Sendinfotojs (view view) {String msg = ((EditText) Findviewbyid (r.id.input_ ET). GetText (). toString (); Invoke the function in JS: Showinfofromjava (msg) Webview.loadurl ("Javascript:showinfofromjava ('" + msg + "')"); }}
(b) Website code:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
Android:webview interacting with JavaScript (calling parameters, passing values)