Android WebView 推送通知?

Android WebView push notification?

我需要通过 android 网络视图发送通知(不一定是 推送 通知)。我看到 Notification APIMDN 上的 Android Webview 不兼容。我看到的其他 API 似乎是基于 window.notification.

有人知道通过 android 网络视图发送通知的 API 或 JS 吗?

我在 6 个月前看到 this post,除了模糊提到 firebase 之外,基本上没有 activity。这会有帮助吗?

感谢您的回答!

我没有足够的 "reputation" 来 post 评论,但这对你有用吗?

希望您可以通过其中一个示例使其发挥作用

一个简单的解决方法使用 JSInterafce - 将 webview 与本机通信。tutorial

在该 JSInterface 传递中,通知所需的参数,然后使用 android 系统通知 API 生成通知。

阅读 Binding JavaScript code to Android code 的文档条目。

这允许您使用 javascript 触发 android 代码的执行。

首先你必须在android上注册Javascript接口,这样你就可以从javascript触发android代码].

JAVA

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");

并定义一个方法,如果 javascript 被调用,它会执行您的操作。在这个例子中显示祝酒词。

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 触发 android 代码:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>

我自己没试过。但是我会尝试创建一个 javascript 方法,它会在一定的时间间隔内向服务器发出 ajax 请求,并检查是否有新的通知要发送,如果为真,则调用 android 代码来显示消息。

但是,您必须确保只以某种方式显示一次通知...也许设置一个包含通知 ID 的 cookie 并将其设置为 true,这样 android 代码就不会被触发再次.

您需要提供通知,例如 JSON 格式的 .json 文件。您可以将该 .json 文件上传到您的网络服务器某处。然后将内容传递给android并进行相应的解析。