java调用js,js调java

java不通过webview解析js,得到返回结果
引入解析包Rhino https://developer.mozilla.org/zh-CN/docs/Mozilla/Projects/Rhino/Download_Rhino
代码示例如下:

package com.nmbb.example.sampleexecutejs;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView text1 = (TextView) findViewById(android.R.id.text1);
        TextView text2 = (TextView) findViewById(android.R.id.text2);
        String js = "function getResult(objs) {var obj = JSON.parse(objs);var result = {};if (!!obj && obj != null) {result = {listObj: obj.recentContactList,count: obj.count,totalPage: obj.totalPage,currentPage: obj.currentPage};}return JSON.stringify(result);}";
        //text1.setText(ScriptUtils.runScript(this,js, "getParameters", new String[] {"3"}));
        //JAVA执行调用JS返回数据 start
        String str = "function getData(dataStr){ return eval('(' + dataStr + ')').avatar; };";
        String dataStr = "{\"userId\":52343617,\"avatar\":\"http://img4.tuniucdn.com/site/m2015/images/member/vipform/default.png\",\"nickName\":\"8082257005\",\"age\":0,\"provinceAndCity\":\"\",\"sex\":9,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true}";
        text1.setText(ScriptUtils.runScript(this,str, "getData", new String[] {dataStr}));
        //end

        //Object obj = ScriptUtils.runScript(this,JAVA_CALL_JS_FUNCTION, "Test", new Integer[] {1});
        //String obj = "{\"count\":45,\"totalPage\":5,\"currentPage\":1,\"recentContactList\":[{\"userId\":27329094,\"avatar\":\"http://m.tuniucdn.com/fb2/t1/G1/M00/14/0B/Cii9EFdhXXSICtLbAEVGA8fkY40AAGkLwIJ9RQARUYb548_w200_h200_c1_t0.jpg\",\"nickName\":\"卓乐翔\",\"age\":25,\"provinceAndCity\":\"浙江绍兴\",\"sex\":0,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true},{\"userId\":59779524,\"avatar\":\"http://img4.tuniucdn.com/site/m2015/images/member/vipform/default.png\",\"nickName\":\"会飞的小天使\",\"age\":23,\"provinceAndCity\":\"湖北黄冈\",\"sex\":0,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true},{\"userId\":3215797,\"avatar\":\"http://m.tuniucdn.com/filebroker/cdn/prd/53/7a/537acbe2e3e2c16ce187b07e627dd9e8_w200_h200_c1_t0.jpg\",\"nickName\":\"小飞侠呐\",\"age\":25,\"provinceAndCity\":\"江苏南京\",\"sex\":1,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true},{\"userId\":3678064,\"avatar\":\"http://m.tuniucdn.com/fb2/t1/G2/M00/63/3C/Cii-TlfU4OqICKBJAA9L9lGAMOgAACR3gHMvREAD0wO624_w200_h200_c1_t0.jpg\",\"nickName\":\"摄影师刘夏\",\"age\":33,\"provinceAndCity\":\"北京朝阳\",\"sex\":0,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true},{\"userId\":28957625,\"avatar\":\"http://m.tuniucdn.com/fb2/t1/G1/M00/4B/0D/Cii9EFh9qYWIIxmCAAj8lgpJYfwAAHAvAFuztkACPyu602_w200_h200_c1_t0.jpg\",\"nickName\":\"奶茶泡馄饨\",\"age\":27,\"provinceAndCity\":\"江苏南京\",\"sex\":1,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true},{\"userId\":30646565,\"avatar\":\"http://m.tuniucdn.com/fb2/t1/G1/M00/2A/BB/Cii9EVbj3myIVg30AAEzyYdLMMAAAClbAFQNX4AATPh685_w200_h200_c1_t0.jpg\",\"nickName\":\"川西自由行\",\"age\":45,\"provinceAndCity\":\"四川成都\",\"sex\":1,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true},{\"userId\":57424800,\"avatar\":\"http://m.tuniucdn.com/fb2/t1/G2/M00/9B/47/Cii-Tlfzj2yIRiDpAAELoJ4iZIUAADDHQCbb6AAAQu4177_w200_h200_c1_t0.jpg\",\"nickName\":\"吐鲁番旅游\",\"age\":0,\"provinceAndCity\":\"新疆吐鲁番\",\"sex\":1,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true},{\"userId\":59400800,\"avatar\":\"http://img4.tuniucdn.com/site/m2015/images/member/vipform/default.png\",\"nickName\":\"仔仔2016\",\"age\":0,\"provinceAndCity\":\"\",\"sex\":1,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true},{\"userId\":59512489,\"avatar\":\"http://m.tuniucdn.com/fb2/t1/G2/M00/55/6C/Cii-T1hOZFeIBFP4AAchJdextOkAAFb0gMRjLAAByE9372_w200_h200_c1_t0.jpg\",\"nickName\":\"凌月JING\",\"age\":28,\"provinceAndCity\":\"湖北武汉\",\"sex\":0,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true},{\"userId\":1762829,\"avatar\":\"http://m.tuniucdn.com/filebroker/cdn/prd/e3/81/e3814243fa45a7a6359691ba3156ee2a_w200_h200_c1_t0.jpg\",\"nickName\":\"风的呢喃\",\"age\":53,\"provinceAndCity\":\"湖南益阳\",\"sex\":0,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true}]}";
        //text1.setText(ScriptUtils.runScript(this,js, "getResult", new Object[] {obj}));
        //js执行调用java返回展示数据 start
        text2.setText(ScriptUtils.runScript(this,JS_CALL_JAVA_FUNCTION_2, "Test", new Object[] {new Test(),"我是js call java"}));
        //end
    }

    /** Java执行js的方法 */
    private static final String JAVA_CALL_JS_FUNCTION = "var a = 1;function Test(str){ a = parseInt(str) + 1;return a; }";

    /** js调用Java中的方法 */
    private static final String JS_CALL_JAVA_FUNCTION = //
    "var ScriptAPI = java.lang.Class.forName(\"" + ScriptUtils.class.getName() + "\", true, javaLoader);" + //
        "var methodRead = ScriptAPI.getMethod(\"jsCallJava\", [java.lang.String]);" + //
        "function jsCallJava(url) {return methodRead.invoke(null, url);}" +
        "function Test(str){ return jsCallJava(str); }";

    /** js调用Java中的方法 */
    private static final String JS_CALL_JAVA_FUNCTION_2 = //
            "var ScriptAPI = java.lang.Class.forName(\"com.nmbb.example.sampleexecutejs.Test\", true, javaLoader);" + //
                    "var methodRead = ScriptAPI.getMethod(\"getStr\", [java.lang.String]);" + //
                    "function jsCallJava(obj,str) {return methodRead.invoke(obj, str);}" +
                    "function Test(obj,str){ return jsCallJava(obj,str); }";

    /**
     * 执行JS
     * 
     * @param js js代码
     * @param functionName js方法名称
     * @param functionParams js方法参数
     * @return
     */
    public String runScript(String js, String functionName, Object[] functionParams) {
        Context rhino = Context.enter();
        rhino.setOptimizationLevel(-1);
        try {
            Scriptable scope = rhino.initStandardObjects();

            ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(MainActivity.this, scope));
            ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(MainActivity.class.getClassLoader(), scope));

            rhino.evaluateString(scope, js, "MainActivity", 1, null);

            Function function = (Function) scope.get(functionName, scope);

            Object result = function.call(rhino, scope, scope, functionParams);
            if (result instanceof String) {
                return (String) result;
            } else if (result instanceof NativeJavaObject) {
                return (String) ((NativeJavaObject) result).getDefaultValue(String.class);
            } else if (result instanceof NativeObject) {
                return (String) ((NativeObject) result).getDefaultValue(String.class);
            }
            return result.toString();//(String) function.call(rhino, scope, scope, functionParams);
        } finally {
            Context.exit();
        }
    }

    public static String jsCallJava(String url) {
        return  url + "农民伯伯 js call Java Rhino";
    }
}
public class ScriptUtils {

    /**
     * 执行JS
     *
     * @param js js代码
     * @param functionName js方法名称
     * @param functionParams js方法参数
     * @return
     */
    public static String runScript(Object obj,String js, String functionName, Object[] functionParams) {
        Context rhino = Context.enter();
        rhino.setOptimizationLevel(-1);
        try {
            Scriptable scope = rhino.initStandardObjects();

            ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(obj, scope));
            ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(obj.getClass().getClassLoader(), scope));

            rhino.evaluateString(scope, js, "test", 1, null);

            Function function = (Function) scope.get(functionName, scope);

            Object result = function.call(rhino, scope, scope, functionParams);
            if (result instanceof String) {
                return (String) result;
            } else if (result instanceof NativeJavaObject) {
                return (String) ((NativeJavaObject) result).getDefaultValue(String.class);
            } else if (result instanceof NativeObject) {
                return (String) ((NativeObject) result).getDefaultValue(String.class);
            }
            return result.toString();//(String) function.call(rhino, scope, scope, functionParams);
        } finally {
            Context.exit();
        }
    }


    public static Object runScript2(Object obj,String js, String functionName, Object[] functionParams) {
        Context rhino = Context.enter();
        rhino.setOptimizationLevel(-1);
        try {
            Scriptable scope = rhino.initStandardObjects();

            ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(obj, scope));
            ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(obj.getClass().getClassLoader(), scope));

            rhino.evaluateString(scope, js, "test", 1, null);

            Function function = (Function) scope.get(functionName, scope);

            Object result = function.call(rhino, scope, scope, functionParams);
            return result;
        } finally {
            Context.exit();
        }
    }

    public static String jsCallJava(String url) {
        return "农民伯伯 js call Java Rhino";
    }

    public static String getSessionId(){
        return "sessionid";
    }

    public static String openUrl(String str){
        return "0000";
    }


    public static String jumpToHomePage(String userId) {
        return "1111";
    }
}

demo地址:
https://download.csdn.net/download/ajun495175289/12367923

你可能感兴趣的:(java调用js,js调java)