android: call javascript from java problem
I want to know if there is way to call javascript from java on android? In my program, I interact java and javascript together. I am using java to receive response(json data) from TCP server and save them into a file. In webview I am using javascript jQuery getJSON() function to retrieve that file and using jQuery plot chart library to draw chart. Now, there is no relationship between java and javasc开发者_开发问答ript. Every time when I update data and file, I still need to click a button in webview to trigger the draw function. I want the programmes to be smart and handy. Is that a way to call or execute javascript from java. I know one way:
Button update = (Button)findViewById(R.id.update);
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
wv.loadUrl("javascript:document.write('hello')");
}
});
But the problem is I already do a index page by loadurl().
final WebView wv = (WebView) findViewById(R.id.webkankan);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("file:///android_asset/index.html");
When I trigger this click event, all contents were gone only a string "hello" there. Another thing is why I need to change webview's type to final to avoid eclipse error. Does this is the problem to trigger my main problem? If so, how can I fix it? Thanks for you patience. Cheers!
For instance you have a javascript
method in the index.html
called loadData()
which reads the file you saved in the java
, then what you can do is wv.loadUrl("javascript:loadData()");
. This actually call the javascript
method and you can then read the file in that method. Hope this solves your problem.
or in simple terms. jus do this webView.loadUrl("javascript:jsmethodname()");
to execute javascript from java.
You can try to communicate java with javascript registering a java object to the webview that is executing the javascript.
The method addJavascriptInterface from Webview will allow you to make available a Java object to the Javascript scope, something like this:
WebView mWebView = new WebView(mContext);
//... webview initialization, js enabling etc.
MyProxyObject obj = new MyProxyObject(); //This object can interchange just basic types, but Strings are basic types
mWebView.addJavascriptInterface(obj,"myproxyobj");
With that code what you will have in the Javascript context you will have an object 'myproxyobj' that is actually a Java object.
Remember, you can interchange just basic types.
For more info check the following url:
http://developer.android.com/guide/webapps/webview.html
Specially check the section: Binding JavaScript code to Android code
Cheers, Francisco
精彩评论