java調(diào)用js,js調(diào)java

java不通過webview解析js察纯,得到返回結(jié)果
引入解析包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執(zhí)行調(diào)用JS返回數(shù)據(jù) 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\":\"川西自由行\(zhòng)",\"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\":\"風(fēng)的呢喃\",\"age\":53,\"provinceAndCity\":\"湖南益陽\",\"sex\":0,\"userTips\":\"\",\"isReceiveMessage\":true,\"isOpenReminder\":true}]}";
        //text1.setText(ScriptUtils.runScript(this,js, "getResult", new Object[] {obj}));
        //js執(zhí)行調(diào)用java返回展示數(shù)據(jù) start
        text2.setText(ScriptUtils.runScript(this,JS_CALL_JAVA_FUNCTION_2, "Test", new Object[] {new Test(),"我是js call java"}));
        //end
    }

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

    /** js調(diào)用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調(diào)用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); }";

    /**
     * 執(zhí)行JS
     * 
     * @param js js代碼
     * @param functionName js方法名稱
     * @param functionParams js方法參數(shù)
     * @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 + "農(nóng)民伯伯 js call Java Rhino";
    }
}
public class ScriptUtils {

    /**
     * 執(zhí)行JS
     *
     * @param js js代碼
     * @param functionName js方法名稱
     * @param functionParams js方法參數(shù)
     * @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 "農(nóng)民伯伯 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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市庐扫,隨后出現(xiàn)的幾起案子懦鼠,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件伸眶,死亡現(xiàn)場離奇詭異,居然都是意外死亡刽宪,警方通過查閱死者的電腦和手機(jī)厘贼,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來圣拄,“玉大人嘴秸,你說我怎么就攤上這事”幼唬” “怎么了岳掐?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長饭耳。 經(jīng)常有香客問我串述,道長,這世上最難降的妖魔是什么哥攘? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任剖煌,我火速辦了婚禮,結(jié)果婚禮上逝淹,老公的妹妹穿的比我還像新娘耕姊。我一直安慰自己,他們只是感情好栅葡,可當(dāng)我...
    茶點故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布茉兰。 她就那樣靜靜地躺著,像睡著了一般欣簇。 火紅的嫁衣襯著肌膚如雪规脸。 梳的紋絲不亂的頭發(fā)上坯约,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天,我揣著相機(jī)與錄音莫鸭,去河邊找鬼闹丐。 笑死,一個胖子當(dāng)著我的面吹牛被因,可吹牛的內(nèi)容都是我干的卿拴。 我是一名探鬼主播,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼梨与,長吁一口氣:“原來是場噩夢啊……” “哼堕花!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起粥鞋,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤缘挽,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后呻粹,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體壕曼,經(jīng)...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年尚猿,在試婚紗的時候發(fā)現(xiàn)自己被綠了窝稿。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡凿掂,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出纹蝴,到底是詐尸還是另有隱情庄萎,我是刑警寧澤,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布塘安,位于F島的核電站糠涛,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏兼犯。R本人自食惡果不足惜忍捡,卻給世界環(huán)境...
    茶點故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望切黔。 院中可真熱鬧砸脊,春花似錦、人聲如沸纬霞。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽诗芜。三九已至瞳抓,卻和暖如春埃疫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背孩哑。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工栓霜, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人横蜒。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓叙淌,卻偏偏與公主長得像,于是被迫代替她去往敵國和親愁铺。 傳聞我的和親對象是個殘疾皇子鹰霍,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,627評論 2 350

推薦閱讀更多精彩內(nèi)容