Cordova 中的后台 Firebase 推送通知 [英] Background Firebase Push Notifications in Cordova

查看:27
本文介绍了Cordova 中的后台 Firebase 推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 phonegap-plugin-push 在 Cordova 应用程序中接收通知.我正在 android Marsh-mellow 上进行部署以进行测试.

I am using a phonegap-plugin-push for receiving notifications in Cordova Application. I am deploying on android Marsh-mellow for testing.

我想查看和存储通过 Firebase 控制台收到的通知的内容 当应用在后台时.

I want to see and store the contents of the Notifications received through Firebase Console when the app is in background.

这是我的代码 -

    document.addEventListener("deviceready",onDeviceReady,false);
    function onDeviceReady(){

       var push = PushNotification.init({ "android": {"senderID": "91254247XXXX"}});

       push.on('registration', function(data) {
           console.log(data.registrationId);
           //document.getElementById("gcm_id").innerHTML = data.registrationId;
       });

       push.on('notification', function(data) {

           alert("On Notification function!!");
             // data.message,
            // data.title,
            // data.count,
            // data.sound,
            // data.image,
            // data.additionalData
            console.log("notification event");
            console.log(JSON.stringify(data));
            alert(JSON.stringify(data));
           //Do something 
       });

       push.on('error', function(e) {
           alert(e);
       });
    }

当应用程序处于前台(在屏幕上)时,我会正确接收内容(标题、消息、数据等),并且可以直接在应用程序的警报框中看到它们.

When the app is in foreground (on screen) I receive the contents (title, message, data, etc.) properly and I am able to see them in alert box directly in the app.

但是当应用程序处于后台(不在屏幕上而是在后台运行)时,我会在通知区域收到通知.当我点击收到的通知时,它会将我重定向到应用程序中最后打开的页面.

But when app is in background (not on screen but running in backround), I get the notification in Notification Area. When I click on the notification received, it is redirecting me to the last opened page in the app.

函数 push.on('notification', function(data) {} 没有被调用.没有显示警报消息.有人可以帮助我如何访问通知消息和数据吗?

The function push.on('notification', function(data) {} is not called. No alert messages are shown. Can someone help me how to access the notification message and data?

推荐答案

经过 2 天的研究,我找到了答案.我们必须在数据字段中将内容可用"设置为 1.否则,如果应用程序在后台,它就不会调用通知块.

I found the answer after 2 days of research. We have to set "content-available" to 1 in the data field. Else it wont call on notification block if app is in background.

而且目前无法通过 Google Firebase 控制台做到这一点.

And this is not possible as of now through Google Firebase Console.

我们必须发送我们的自定义负载消息(数据或通知或两者)单独使用任一 firebase 服务器.

We have to send our custom payload messages (data or notification or both) seperately using any one of the firebase servers.

详细信息可以在插件的 GitHub 页面 关于后台通知.

Detailed info can be found on the plugin's GitHub Page on background notifications.

我使用了 NodeJs firebase-admin.我遵循了这些 设置指南 和这些 发送消息的步骤,它对我有用.

I used NodeJs firebase-admin. I followed these setup guidelines and these steps for sending messages and it worked for me.

这是我的工作代码(NodeJS)-

Here is my working code (NodeJS) -

var admin = require("firebase-admin");

var serviceAccount = require("pushnotificationapp-xxxxx.json"); //this is the service account details generated from server

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://pushnotificationappxxxxx.firebaseio.com/" //your database URL here.
});

var registrationToken = "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX....."; //registration token of the device
var payload ={
    "data": {
        "title": 'Test Push',
        "message": 'Push number 1',
        "info": 'super secret info',
        "content-available": '1' //FOR CALLING ON NOTIFACATION FUNCTION EVEN IF THE APP IS IN BACKGROUND
    }
};

//send the notification or message
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
    console.log("Successfully sent message:", response);
})
.catch(function(error) {
    console.log("Error sending message:", error);
});

更新:

我也使用 php 服务器实现了相同的功能.这是我使用 发送通知的工作 php 代码HTTP POST 到 FCM 服务器-

I implemented the same using php server too. Here is my working php code for sending notifications using HTTP POST to FCM server-

<?php

$url = 'https://fcm.googleapis.com/fcm/send';

$data = 
    array(
          "to" => "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX.....",
          "data" => array(
                "title"=> 'Test Push',
                "message"=> 'Push number 1',
                "info"=> 'super secret info',
                "content-available"=> '1')

   );

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => array("Content-Type:application/json",
        "Authorization:key=AAAA1HfFM64:APA91XXXX...."), //this is the server authorization key from project settings tab in your Firebase Project
        'method'  => 'POST',
        'content' => json_encode($data)
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === FALSE) { echo "Caught an error"; }
else{
    echo $result;
}
?>

这篇关于Cordova 中的后台 Firebase 推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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