本土code在Android中的webapps调用JS [英] Native code calling JS in Android webapps

查看:104
本文介绍了本土code在Android中的webapps调用JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个Android的网络应用程序(APP的,我不会上传至网络,但将HTML + JS里面的应用程序资源)。这意味着,图形用户界面将是HTML5,我会用另一种原生线程从麦克风读取并希望派分析文本的HTML5 / JS code。

I am writing an Android "web" app (I will not upload the APP to the web, but set the HTML+JS inside the application resources). That means, the GUI will be HTML5, and I will use another "native" thread to read from the microphone and hopefully send the "parsed text" to the HTML5/JS code.

这可能吗?在Android code,我看我怎么可以调用本机code的JS(和我想的相反)。

Is this possible? In the Android code, I see how can I call native code from JS (and I want the opposite).

http://developer.android.com/guide/webapps/webview.html

推荐答案

是的,Android的岩石这个呢。

Yes, Android rocks at this actually.

我是从一个随机的例子应用程序,我做了张贴例如code,但这应该让你去。

I'm posting example code from a random example app that I made but this should get you going.

让我们通过假设你有全局变量来你的WebView控制类启动:

Lets start by supposing you have to global variable to your webview controlling class:

String name = "John";
String lastName = "Doe";

在Android类控制的WebView(在的onCreate()或当你设置你的WebView):

In the Android class controlling the webview (during onCreate() or when you setup your webview):

webView.addJavascriptInterface(new JavaScriptInterface(), "android")

内部类的web视图控制类:

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();
    }
}

完蛋了针对Android的一面,现在通过JavaScript中使用它:

Thats it for the Android side, now to use it through Javascript:

要通过JavaScript获取名称和名字:

To get the name and lastname through JavaScript:

if (window.android){
    name = window.android.getName();
    lastName = window.android.getLastName();
}

如果你想提高敬酒,设置一个JavaScript其功能是:

If you want to raise the toast, set a javascript whose function would be:

if (window.android){
    window.android.onJavascriptButtonPushed("Hello");
}

编辑:

我还没有尝试过这一点,但一个<一个href="http://stackoverflow.com/questions/4325639/android-calling-javascript-functions-in-webview">search得到这个,尝试一下,它应该工作。

I havent tried this, but a search yielded this, try it out, it should work.

如果您想使用它在另一个方向:

记者:

function testEcho(message){
     window.JSInterface.doEchoTest(message);
}

Android的:

Android:

myWebView.loadUrl("javascript:testEcho('Hello World!')");

这篇关于本土code在Android中的webapps调用JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆