我有一个问题。 HTML5 页面可以与 Android 中的原生组件交互吗?
我想要实现的是在显示内容列表的 HTML5 页面上。我想创建一个通知,告知某些内容已到达。?
我猜,一种方法是使用 webview 并在那里显示我的 HTML5 内容,但如何从 webview 获取回调,以便我可以通过可访问的通知栏通知用户某些内容已到达使用原生 Android 编码?
我已经知道如何在 android 上创建通知以及如何创建 webview,我只需要找到一种方法将数据从 html5 页面发送到 android 组件,反之亦然。
这可以实现还是过于雄心勃勃?
最佳答案
是的,您可以通过 JavaScript 接口(interface)实现这一点。通过此 JavaScript 可以调用您附加的接口(interface)中定义的函数。
http://developer.android.com/guide/webapps/webview.html
在您的 Activity
中:
WebAppInterface mInterface;
public void onCreate() {
mInterface = new WebAppInterface(this);
mWebView.addJavascriptInterface(mInterface, "MyAndroidInterface")
}
现在定义一个调用将转到的对象:
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
现在在 Javascript
中您可以执行以下操作:
MyAndroidInterface.showToast("hello world");
返回的方式(从native
到Javascript
)您可以通过Javascript注入(inject)
来完成。
在 Javascript
中定义函数:
function helloBack(param) {
}
现在你可以调用mWebView.loadUrl("javascript:helloBack(hi);");
关于android - HTML5可以访问原生组件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16319974/