我是 Android 新手,正在尝试设置 Android Webview 以加载 javascript 函数并将结果返回给回调函数。
请参阅下面的代码
public class AWebViewActivity extends Activity {
/**
* Defines an Interface to call Syntax Highlighting Javascript and return the result
* to a string by calling the call back function.
*/
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
//add other interface methods to be called from JavaScript
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public void receiveValueFromJs(String str) {
//do something useful with str
Toast.makeText(mContext, "Received Value from JS: " + str,Toast.LENGTH_LONG).show();
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Try WebView
WebView webView = (WebView) findViewById(R.id.editor_view);
//webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
// RiNxX's suggestion
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url){
view.loadUrl("javascript:getValue()");
}
});
webView.addJavascriptInterface(new JavaScriptInterface(this), "MyAndroid");
webView.loadUrl("file:///mnt/sdcard/a.html");
//SystemClock.sleep(1000);
//webView.loadUrl("javascript:getValue()");
}
}
HTML 文件如下所示:
<html>
<head>
</head>
<body>
<script type="text/javascript">
function getValue()
{
var val="Amith Raravi";
MyAndroid.receiveValueFromJs(val);
}
</script>
Hey ya
</body>
</html>
我还添加了 INTERNET 权限作为 Manifest 元素的子元素。我浏览了 StackOverflow 上发布的其他问题,并将脚本移至 HTML 正文。
添加 RiNxX 建议的更改后,应用程序关闭(它不执行回调),我在 LogCat 中收到以下警告
JNI WARNING: jarray 0x405414e8 points to non-array object (Ljava/lang/String;)
I/dalvikvm(361): "WebViewCoreThread" prio=5 tid=9 NATIVE
I/dalvikvm(361): | group="main" sCount=0 dsCount=0 obj=0x4051d580 self=0x29a1a8
I/dalvikvm(361): | sysTid=370 nice=0 sched=0/0 cgrp=default handle=2728672
I/dalvikvm(361): | schedstat=( 277421205 460097188 88 )
I/dalvikvm(361): at android.webkit.BrowserFrame.stringByEvaluatingJavaScriptFromString(Native Method)
I/dalvikvm(361): at android.webkit.BrowserFrame.stringByEvaluatingJavaScriptFromString(Native Method)
I/dalvikvm(361): at android.webkit.BrowserFrame.loadUrl(BrowserFrame.java:246)
I/dalvikvm(361): at android.webkit.WebViewCore.loadUrl(WebViewCore.java:1570)
I/dalvikvm(361): at android.webkit.WebViewCore.access$1400(WebViewCore.java:53)
I/dalvikvm(361): at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:956)
I/dalvikvm(361): at android.os.Handler.dispatchMessage(Handler.java:99)
I/dalvikvm(361): at android.os.Looper.loop(Looper.java:123)
I/dalvikvm(361): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:629)
I/dalvikvm(361): at java.lang.Thread.run(Thread.java:1019)
E/dalvikvm(361): VM aborting
我已经做了一天多了。任何帮助都将受到欢迎:)