如何使用简单的推送通知唤醒应用程序?

时间:2014-12-07 23:12:15

标签: javascript firefox-os simple-push-api

我正在学习Firefox OS应用程序的简单推送A​​PI。我了解这将允许我启动一个在收到通知时关闭的应用程序。在this文档之后,我能够创建一个可以注册端点并接收通知的工作应用程序,但这仅在应用程序打开时才有效。我甚至可以关闭应用程序,再次打开它而不注册新的端点,发送到前一个端点的通知继续工作;但如果应用程序关闭则没有任何反应。

我正在运行Firefox OS 1.4的手机上进行测试。

这是我目前的代码:

的index.html

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, user-scalable=no">
        <meta charset="UTF-8">
        <script>
            navigator.mozSetMessageHandler('push', function(message) {
                document.getElementById('log').innerHTML = new Date();
            });
            navigator.mozSetMessageHandler('push-register', function(e) {
                register();
            });
            function register() {
                var endpoint;
                var request = navigator.push.register();
                request.onsuccess = function(e) {
                    endpoint = e.target.result;
                    document.getElementById('log').innerHTML = endpoint;
                    var xmlhttp=new XMLHttpRequest();
                    xmlhttp.open("GET",'http://192.168.1.6:8080/Servlet/endpoint?asd=' + encodeURIComponent(endpoint),true); //This sends the endpoint to my computer so I can ping it with curl.
                    xmlhttp.send();
                }
            }
        </script>
    </head>
    <body>
        <h1>Push</h1>
        <button type="button" onclick="register();">REGISTER</button>
        <br>
        <span id="log"></span>
    </body>
</html>

manifest.webapp

{
    "name": "Push",
    "description": "push notifications.",
    "launch_path": "/index.html",
    "version": "1.0",
    "developer": {
        "name": "Lufte",
        "url": "https://github.com/lufte"
    },
    "permissions": {
        "push": {"description": "To receive notifications about the newest phone releases"}
    },
    "messages": [
        {"push": "/index.html"},
        {"push-register": "/index.html"}
    ]
}

1 个答案:

答案 0 :(得分:0)

您必须添加推送消息处理程序来处理推送消息。喜欢这个

if (window.navigator.mozSetMessageHandler) {
    window.navigator.mozSetMessageHandler('push', function(e) {
        console.log('My endpoint is ' + e.pushEndpoint);
        console.log('My new version is ' +  e.version);
        //Remember that you can handle here if you have more than
    });
} else {
  // No message handler
}

有关详细信息,请参阅this section

快乐编码