Thứ Sáu, 20 tháng 9, 2013

Tương tác javascript và android native


4down voteaccepted
Yes, Android rocks at this actually.
I'm posting example code from a random example app that I made but this should get you going.
Lets start by supposing you have to global variable to your webview controlling class:
String name = "John";
String lastName = "Doe";
In the Android class controlling the webview (during onCreate() or when you setup your webview):
webView.addJavascriptInterface(new JavaScriptInterface(), "android")
Inner class to your webview controlling class:
/**
* Sets up the interface for getting access to Latitude and Longitude data
* from device
**/
private class JavaScriptInterface {
    public String getName() {
        return name;
    }
    public String getLastName() {
        return lastName;
    }
    public void onJavascriptButtonPushed(String text) {
        Toast.makeText(WebViewControllingClass.this, "The text of the pressed button is: "+text,Toast.LENGTH_SHORT).show();
    }
}
Thats it for the Android side, now to use it through Javascript:
To get the name and lastname through JavaScript:
if (window.android){
    name = window.android.getName();
    lastName = window.android.getLastName();
}
If you want to raise the toast, set a javascript whose function would be:
if (window.android){
    window.android.onJavascriptButtonPushed("Hello");
}
Edit:
I havent tried this, but a search yielded this, try it out, it should work.
If you want to use it in the other direction:
JS:
function testEcho(message){
     window.JSInterface.doEchoTest(message);
}
Android:
myWebView.loadUrl("javascript:testEcho('Hello World!')");

Không có nhận xét nào:

Đăng nhận xét