Android WebView interacts with JavaScript to implement web apps
Source: Internet
Author: User
<span id="Label3"></p>When we go to develop a web-based Android app, the first thing we need to deal with is the interaction with javascript, what Android needs to do is to open up certain interfaces for JavaScript calls in the web, to open popup functions, Toast, interface jumps, and so on, so that our web view is the original Android interface, and this web code can be embedded in the iphone client, that is, the Android and iOS client is only to provide a common web-use framework, The business is handled by the web-side, wouldn't it be developed once and can be run Everywhere. however, all of this is something, and let's first implement the WebView and JavaScript interaction Issues. Here I take the Android app as an Example.<br>1. First create an empty Android project in eclipse, i'll name it jsinteraction, Locate and open the Androidmanifest.xml file and add a Android.permission.WRITE_EXTERNAL_STORAGE permission in the Permissions. 2. Here I have added a master page activity_main.xml, a main activity mainactivity.java, and a class Jsoperator.java that provides various functions for JavaScript calls. The main directory structure as shown in the home page activity_main.xml code is shown below, with only one WebView<pre class="html" name="code"><pre class="html" name="code"><?xml version= "1.0" encoding= "utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" match_parent " android:o rientation= "vertical" > <webview android:id= "@+id/webview" android:layout_width= "match_parent " android:layout_height=" match_parent "/></linearlayout></pre></pre>The code for Mainactivity.java is shown below, which means adding an object to be called by js, whose alias is jsinteraction, so that the corresponding method can be called as long as the jsinteraction.< method name > () is written in Js. WebView will load the login.html under the Loginjs folder in the assets folder, which will be created Later.<pre class="java" name="code">Package Com.yld.jsinteraction;import Android.support.v7.app.actionbaractivity;import android.webkit.WebSettings; Import Android.webkit.webview;import Android.annotation.suppresslint;import Android.os.bundle;public class Mainactivity extends actionbaractivity {private WebView WebView; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); setcontentview (r.layout.activity_main); This.webView = ( WebView) This.findviewbyid (r.id.webview); This.initializewebview ();} @SuppressLint ({"newapi", "setjavascriptenabled"}) private void Initializewebview () {webview.addjavascriptinterface ( New Jsoperator (mainactivity.this), "jsinteraction"); try {String url = "file:///android_asset/LoginJs/login.html"; WebSettings websettings = webview.getsettings (); websettings.setjavascriptenabled (true); Websettings.setallowfileaccess (true); websettings.setallowfileaccessfromfileurls (true); this.webView.loadUrl (url );} Catch (Exception e) {e.printstacktrace ();}}}</pre>The code for Jsoperator.java is as follows <pre class="java" name="code">Package Com.yld.jsinteraction;import Org.json.jsonobject;import Android.app.alertdialog;import Android.app.alertdialog.builder;import Android.content.context;import Android.content.dialoginterface;import Android.content.dialoginterface.onclicklistener;import Android.webkit.javascriptinterface;public class JsOperator {private context context;public jsoperator (context Context) {this.context = context;} /** * Popup message dialog box */@JavascriptInterfacepublic void showDialog (String message) {alertdialog.builder builder = new Builder (con text); builder.setmessage (message); builder.settitle ("hint"); builder.setpositivebutton ("confirm", new Onclicklistener () {@ overridepublic void OnClick (dialoginterface dialog, int which) {}}); Builder.setnegativebutton ("cancel", New Onclicklistener () {@Overridepublic void onClick (dialoginterface dialog, int which) {dialog.dismiss ();}}); Builder.create (). Show (); /** * Get login username and password * @return json-formatted string */@JavascriptInterfacepublic string getlogininfo () {try{jsonobject login = new Jsono Bject (); login.put ("Username", "YLD"), login.put ("Password", "111"); return login.tostring ();} Catch (Exception e) {e.printstacktrace ();} Return null;}}</pre>Jsoperator provides two methods, one way to pop up the dialog, and the other is to return a JSON string of login information, and both methods are labeled @javascriptinterface, which is more important, Because in a lower version, if you do not declare it to be a method that JavaScript can call, JS cannot be called.<br>3. Create the Loginjs folder under the Assets folder and create two files under it login.html,login.jslogin.html a user name password entry box and a login button, the code is as follows<pre class="html" name="code"><pre class="html" name="code"><! DOCTYPE html>
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service