Mixed JSON's Android Android application

Through the WebView to call java method in the javascript code, javascript code java code execution, data exchange between the two by json

Set the WebView widget

// connect to our browser so we can manipulate it
browser = (WebView) findViewById(R.id.calculator);

// set a webview client to override the default functionality
browser.setWebViewClient(new wvClient());

// get settings so we can config our WebView instance
WebSettings settings = browser.getSettings();

// JavaScript?  Of course!

// clear cache

// this is necessary for "alert()" to work
browser.setWebChromeClient(new WebChromeClient());

// add our custom functionality to the javascript environment
browser.addJavascriptInterface(new CalculatorHandler(), "calc");

// uncomment this if you want to use the webview as an invisible calculator!

// load a page to get things started

// allows the control to receive focus
// on some versions of Android the webview doesn't handle input focus properly
// this seems to make things work with Android 2.1, but not 2.2
// browser.requestFocusFromTouch();

Activity will be a range variable named browser's tied to the WebView control. WebView is a very complex class, highly customizable. For example, you need to set number of classes to be associated with the web browser is expected to function. This is the programmer must invest some effort to get some useful function in the world. However, this custom is no limit. For purposes of this application, WebView control has been minimal deployment.

WebViewClient provide hooks to capture a variety of events, these events include the beginning and end of the page is loaded, the form re-submitted, keyboard tracking and interception, and manipulation of programmers like many other events. Similarly, you need WebChromeClient an example of very useful for allowing such as alert () JavaScript function like function. WebSettings to enable the control using JavaScript.

JavaScript Interface Connection

Activity in the next step is to enable Java code to HTML files with WebView management interaction in the JavaScript code. This is done by calling addJavascriptInterface () method to complete, as shown in Listing 4.

The function of the parameter is a Java class instance and a name space identifier. For example, for this application, you define a calc name space, and achieving a class called CalculatorHandler the code shown in Listing 5.

Listing 5. CalculatorHandler achieve

// Javascript handler
final class CalculatorHandler
    private int iterations = 0;
    // write to LogCat (Info)
    public void Info(String str) {
    // write to LogCat (Error)
    public void Error(String str) {
    // sample to retrieve a custom - written function with the details provided
    // by the Android native application code
    public String GetSomeFunction()
        return "var q = 6;function dynamicFunc(v) { return v + q; }";
    // Kill the app
    public void EndApp() {
    public void setAnswer(String a)
        Log.i(tag,"Answer [" + a + "]");
    public int getIterations()
        return iterations;
    public void SendHistory(String s)
        Log.i("Calc","SendHistory" + s);
        try {
            JSONArray ja = new JSONArray(s);
            for (int i=0;i<ja.length();i++) {
                Log.i("Calc","History entry #" + (i+1) + " is [" + ja.getString(i)+ "]");
        } catch (Exception ee) {

In the JavaScript environment, access CalculatorHandler by window.calc.methodname grammar approach. For example, CalculatorHandler implement a called Info () method, which accepts a string parameter and the write in the Application log. Access this method from the JavaScript environment, you can use syntax like this: window.calc.Info ("write this string to the application log !");。

Basic understanding of how to call Java code from JavaScript code, we will look at the index.html file in Listing 6 to see how the various methods being called.

Listing 6. WebView control is rendered (and executed) index.html

<meta name="viewport" content="width=device-width,initial-scale=0.25,
    user-scalable=yes" />
<title>Android to JavaScript with JSON</title>
<script language="JavaScript">
var cmdHistory = new Array();
function startup() {
    try {
        window.calc.Info("Starting up....");
        cmdHistory[cmdHistory.length] = "startup";
    } catch (ee) {

function PerformSimpleCalculation(formula) {
    try {
        cmdHistory[cmdHistory.length] = "PerformSimpleCalculation";
        var answer = eval(String(formula));
        document.getElementById('data').value = answer;
    }    catch (ee)     {
function PerformComplexCalculation(andmethod) {
    try    {
         * argument to this function is a single object with 2 "members or properties"
         * operation: this is a string naming what we want the function to do.
         * array of arguments: this is an array of integers
        if (andmethod.operation == "addarray") {
            cmdHistory[cmdHistory.length] = "PerformCompleCalculation-addarray";
            var i;
            var result = 0;
            for (i=0;i<andmethod.arguments.length;i++) {
                result += andmethod.arguments[i];
            document.getElementById('data').value = result;
        if (andmethod.operation == "multarray") {
            cmdHistory[cmdHistory.length] = "PerformCompleCalculation-multarray";
            var i;
            var result = 1;
            for (i=0;i<andmethod.arguments.length;i++) {
                result *= andmethod.arguments[i];
            document.getElementById('data').value = result;
    }    catch (ee)    {
function dynamicfunction()
    try {
        cmdHistory[cmdHistory.length] = "PerformCompleCalculation-dynamic";
        var result = dynamicFunc(parseInt(document.getElementById('data').value));
        document.getElementById('data').value = result;
    }catch (ee) {
<body >
<h3>Running in Web View :)</h3>
this is some sample text here <br />
<input type="text" value="starting value"><br />
 Error</button><br />
    Many Calls</button>
<button>Kill This
 App</button><br />

Closer look at the list at the end of the button handler 6. Basically, these are called window.calc button handler method name space, these methods AndroidJSON.java the CalculatorHandler class implementation.

Listings 5 and 6 work together to demonstrate the JavaScript environment and the Java source file initialization code to achieve interaction. But how to initialize the code from the Activity you want to occur in the WebView step?

Should now be more in-depth look at Java code.

Insert JavaScript code

From a mathematical formula is passed to the JavaScript code to calculate the beginning of such a task. JavaScript's greatest (and most dangerous) is one of the characteristics eval () function. eval () function allows a string of code run time. In this case, you received from the EditText control is a string and passed to the JavaScript environment calculations. Specifically, we call in Listing 6 PerformSimpleCalculation () function.

AndroidJSON.java Listing 7 contains the code that handles button to select.

Listing 7. From Java called PerformSimpleCalculation () JavaScript function

  btnSimple.setOnClickListener(new OnClickListener()
       public void onClick(View v) {
         Log.i(tag,"onClick Simple");
         // Perform action on click
            String formulaText =  formula.getText().toString();
            Log.i(tag,"Formula is [" + formulaText + "]" );
            browser.loadUrl("javascript:PerformSimpleCalculation(" + formulaText + ");");
         catch (Exception e)
               Log.e(tag,"Error ..." + e.getMessage());

No matter how many rows this way, where the only concern is browser.loadurl () line, which passes a format string: javascript: <code to execute>.

This JavaScript code is injected into the WebView's current page and execute. So, Java code can execute JavaScript code defined in the WebView was.

In the Simple example, passed a string. However, when the need to address the more complex the structure of how to do it? This is where JSON can come in handy. Listing 8 shows PerformComplexCalculation () function call, the function see Listing 6.

Listing 8. By passing a JSON object to call a more complex function

btnComplex.setOnClickListener(new OnClickListener()
     public void onClick(View v) {
         Log.i(tag,"onClick Complex");
         // Perform action on click
             String jsonText = "";

             if (flipflop == 0)
                 jsonText = "{ \"operation\" : \"addarray\",\"arguments\" : [1,2,3,4,5,6,7,8,9,10]}";
                 flipflop = 1;
             } else {
                 jsonText = "{ \"operation\" : \"multarray\",\"arguments\" : [1,2,3,4,5,6,7,8,9,10]}";
                 flipflop = 0;
             Log.i(tag,"jsonText is [" + jsonText + "]" );
             browser.loadUrl("javascript:PerformComplexCalculation(" + jsonText + ");");
         catch (Exception e)
             Log.e(tag,"Error ..." + e.getMessage());


Look at the JavaScript function in Listing 6 PerformComplexCalculation. Note that the parameter is not passed in a string, but an object that you create yourself.

* Operation - to deal with the name of the function or procedure
* Arguments - this is a integer array

Object contains only two properties, but can be more complex to meet the higher demand. In this case, PerformComplexCalculation () JavaScript function supports two different operations: addarray and multarray. When these operations in the call to complete its work by calling the function window.calc.setAnswer, the result is passed back to Java code. Here, you see the Java and JavaScript code, two-way data flow.

In this case, you pass a JSON object, but get an experience in dealing with returns from the Java code to the Java string, it helps to convert them into a JavaScript string. This can be the same as in this case the value passed to the String by function to do: eval (String (formula));.

JavaScript eval () function uses the JavaScript string. Without conversion, then, eval function is not used for anything.

For a slightly more complex example, to encourage Hello nice about Dynamic button is selected in the WebView in the code.

To complete code example, look at an array of strings passed to the Java environment from the JavaScript environment.

JSON object exchange

Sample application (index.html) in the JavaScript code to a local function call record level page named cmdHistory array. Each time the function is called, you will add a new entry to the array. For example, when dynamicfunction () is called, a new string is stored: cmdHistory [cmdHistory.length] = "PerformCompleCalculation-dynamic";.

On this method, no particular place; it is just a collection of use data in the page-level example. Perhaps the data is stored in the database Android applications will be useful. How this data back to Java code?

To send a string to an array of objects, you call JSON.stringify function, the array is passed as a parameter. Necessary, stringify function allows customization of a complex object to be formatted a specific property. How is this done on more information, see the explanation json.org

分类:Mobile 时间:2011-01-03 人气:232
blog comments powered by Disqus


  • JAVA in the equals () and hashCode () method 2009-11-02

    Quote In the Java language, equals () and hashCode () using the two functions are closely co-ordinated if you are one of their own design, we must design another one. In most cases, these two functions are not considered, the direct use of their defa

  • Java in the hashcode () and equals () method Detailed 2010-10-05

    Quoted from http://www.cnjm.net/tech/article4731.html For a long afternoon of hashcode () and equals () method, finally have a little bit to understand, write it down and share (zhaoxudong 2008.10.23 Late 21.36). 1. First equals () and hashcode () of

  • Java面试题集锦5:EJB,J2EE,MVC,设计模式,JavaScript,CORBA方面 2015-03-05

    EJB方面 1.EJB2.0有哪些内容?分别用在什么场合? EJB2.0和EJB1.1的区别? 答:规范内容包括Bean提供者,应用程序装配者,EJB容器,EJB配置工具,EJB服务提供者,系统管理员.这里面,EJB容器是EJB之所以能够运行的核心.EJB容器管理着EJB的创建,撤消,激活,去活,与数据库的连接等等重要的核心工作.JSP,Servlet,EJB,JNDI,JDBC,JMS..... 2.EJB与JAVA BEAN的区别? 答:Java Bean 是可复用的组件,对Java Bea

  • jxl error java.lang.NoClassDefFoundError: jxl / write / WriteException method 2010-04-06

    Want to use the jxl export excel, feel more nausea: First of all, jxl.jar heavily dependent on jdk version. I downloaded the latest jar package, import the main method to test later and was told bad version. As the system reasons, I use the jdk5 vers

  • Java multi-threading (11): Synchronized block synchronization method using 2010-12-19

    synchronized keyword has two uses. The first is "Using the Synchronized keyword synchronized class method," a paper presented directly in the definition of the method. Another is the synchronized block. We not only through synchronized block to

  • android webview中使用Java调用JavaScript方法并获取返回值 2013-12-19

    这篇文章主要介绍了android webview中使用Java调用JavaScript方法并获取返回值,本文直接给出代码示例,需要的朋友可以参考下 在android平板上用webview打开一个网页,调用里面的javascript方法,同时相互传参. 网上例子很少啊,基本都不能获取返回值,贴一个自己最后调试完的代码如下: Java: protected void onCreate(Bundle savedInstanceState) { ........ x = (WebView)this.fi

  • Android Webview Java和Javascript安全交互 2015-04-23

    最近要对一个网页的源代码进行检测,Android Webview中没有直接获取网页源代码的接口,传统的addJavascriptInterface方法存在安全隐患,所以研究了一下Java和Javascript的安全交互. Android Webview漏洞 Android Webview有两个非常知名的漏洞: 最近爆出来的UXSS漏洞,可以越过同源策略,获得任意网页的Cookie等信息,Android 4.4以下都有此问题,基本无解,只能重新编译浏览器内核解决,详情可以参考最近移动安全三两事,感

  • Javascript Inheritance discussion (method coverage), and how FireFox3.6.3 compatible (may be FF3.6.3 the BUG) 2010-06-12

    Use prototype.js (1.5.1) to implement Javascript class inheritance, and to upgrade your browser to Firefox3.6.3, found that class inheritance can not be in the new version of FF (3.6.3) to implement the following classes for the use of Javascript Inh

  • JSP comments in the browser view the source code, do not see this interface 2010-12-29

    JSP comments in the browser view the source code, do not see this interface <% - Do not see me, and I was commented code -%> <% - / * * Copyright (c) 2007, Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binar

  • JavaScript how to pass parameters to JavaScript files 2009-09-01

    First, the use of global variables <br /> This is the most simple way, such as Google Adsense: Code <script type="text/javascript"> google_ad_client = 'pub-3741595817388494'; </ script> <script type = "text / javascript

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.870 (s). 12 q(s)