整理自:http://blog.sina.com.cn/s/blog_67ac56e70101ajlp.html
本文實現的是使用WebView調用js代碼,並獲得function的return值
1. 創建自定義的 MyWebView 並繼承 WebView
public class MyWebView extends WebView {
public MyWebView(Context context) {
super(context);
}
public MyWebView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public String stringByEvaluatingJavaScriptFromString(String script) {
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.JELLY_BEAN) {
try{
Field mp = WebView.class.getDeclaredField("mProvider");
mp.setAccessible(true);
Object webViewObject = mp.get(this);
Field wc = webViewObject.getClass().getDeclaredField("mWebViewCore");
wc.setAccessible(true);
Object webViewCore = wc.get(webViewObject);
Field bf = webViewCore.getClass().getDeclaredField("mBrowserFrame");
bf.setAccessible(true);
Object browserFrame = bf.get(webViewCore);
Method stringByEvaluatingJavaScriptFromString = browserFrame.getClass()
.getDeclaredMethod("stringByEvaluatingJavaScriptFromString",
String.class);
stringByEvaluatingJavaScriptFromString.setAccessible(true);
Object obj_value = stringByEvaluatingJavaScriptFromString.invoke(
browserFrame, script);
return String.valueOf(obj_value);
}catch(Exception e) {
e.printStackTrace();
Log.e("!!!","stringByEvaluatingJavaScriptFromString", e);
}
return null;
}else{
try{
Field[]fields= WebView.class.getDeclaredFields();
//由webview取到webviewcore
Field field_webviewcore = WebView.class.getDeclaredField("mWebViewCore");
field_webviewcore.setAccessible(true);
Object obj_webviewcore = field_webviewcore.get(this);
//由webviewcore取到BrowserFrame
Field field_BrowserFrame = obj_webviewcore.getClass().getDeclaredField(
"mBrowserFrame");
field_BrowserFrame.setAccessible(true);
Object obj_frame = field_BrowserFrame.get(obj_webviewcore);
//獲取BrowserFrame對象的stringByEvaluatingJavaScriptFromString方法
Method method_stringByEvaluatingJavaScriptFromString = obj_frame.getClass()
.getMethod("stringByEvaluatingJavaScriptFromString", String.class);
//執行stringByEvaluatingJavaScriptFromString方法
Object obj_value = method_stringByEvaluatingJavaScriptFromString.invoke(
obj_frame,
script);
//返回執行結果
return String.valueOf(obj_value);
}catch(Exception e) {
e.printStackTrace();
Log.e("!!!","stringByEvaluatingJavaScriptFromString", e);
}
return null;
}
}
}
2. 使用
例子代碼:http://download.csdn.net/detail/qqgrid/8210305