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