Android WebView interacts with JavaScript to implement web apps

Source: Internet
Author: User

When we 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 open up certain interfaces for JavaScript calls in the Web, open popup functions, Toast, interface jumps, and so on. In this way, our web view is a genuine native interface for Android. This set of web code can be embedded in the iphone's client. This means that Android and iosclient do not provide a common web-use framework, and the business is handled by the Web. This is not to be developed once. can be executed 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.


1. First create an empty Android project in Eclipse, and I'll name it jsinteraction. Locate and open the Androidmanifest.xml file and add a Android.permission.WRITE_EXTERNAL_STORAGE permission to the permissions.

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center ">2. Here I have joined a main page activity_main.xml, a basic activity Mainactivity.java. And a class Jsoperator.java that provides various functions for JavaScript invocation.

The basic folder structure for example, as seen in the

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center "> main page activity_main.xml code such as the following see. Only one webview.

<?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>
The code for Mainactivity.java is seen in the following example.

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center "> represents the object to join for the JS call. Its alias is jsinteraction. So in JS only to write jsinteraction.< method name > () will be able to call the corresponding method. WebView will load the login.html in the Loginjs directory in the assets directory, and this file will be created later.

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 ();}}}
Jsoperator.java code such as the following
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 JSonobject (); Login.put ("Username", "YLD"), Login.put ("Password", "111"); return login.tostring ();} catch (Exception e) {e.printstacktrace ();} return null;}}
Jsoperator provides two methods, one for pop-up dialogs, and the other is to return a JSON string of login information, and both methods are labeled @javascriptinterface, which is more important, Because it is assumed in the lower version number that it is not declared, it is a method that JavaScript can invoke. JS will not be called.


3. Create the LOGINJS directory under the assets directory and create two files under it login.html,login.jslogin.html a usernamepassword input box and a login button. Code such as the following

<! DOCTYPE html>
Use Jsinteraction.getlogininfo () in Login.js's setlogininfo to invoke the interface provided by Android and get login information and populate the user input box with the login information. The login method calls the Jsinteraction.showdialog ("Login start ...") to invoke the interface of the pop-up dialog provided by the Android side.
var login = (function () {function Login () {}login.prototype.login = function () {jsinteraction.showdialog ("Login start ... ");} Login.prototype.setLoginInfo = function () {var Logininfojson = Jsinteraction.getlogininfo ();//Parse JSON string var logininfo = Eval ("(" +logininfojson+) ");d Ocument.getelementbyid (" txtUserName "). Value = Logininfo. Username;document.getelementbyid ("Txtpassword"). Value = Logininfo. Password;} return Login;}) () var loginobj = new Login (); Window.onload=function () {loginobj.setlogininfo ();}

4.Html and client creation is complete, and execution effects such as the following
Click Loginbutton

SOURCE Download page: http://download.csdn.net/detail/leyyang/8995887

Android WebView interacts with JavaScript to implement web apps

Related Article

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.