在科尔多瓦背景Firebase推送通知 [英] Background Firebase Push Notifications in Cordova

查看:562
本文介绍了在科尔多瓦背景Firebase推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 phonegap-plugin-push 接收Cordova应用程序中的通知。我正在部署Android Marsh-mellow进行测试。



我想查看和存储通过 Firebase Console

这里是我的代码 -

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

var push = PushNotification.init({android:{senderID:91254247XXXX}});
$ b push.on('registration',function(data){
console.log(data.registrationId);
//document.getElementById(\"gcm_id\").innerHTML = data.registrationId;
});
$ b 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东西
});
$ b push.on('error',function(e){
alert(e);
});

当应用处于前景状态时)我收到的内容(标题,消息,数据等),我可以直接在应用程序中看到他们在警报框中。但是,当应用程序处于后台(不在屏幕上但在后台运行)时,我会在通知区域中收到通知。 当我点击收到的通知,它将重定向到应用程序中最后打开的页面。


$ b

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

经过2天的研究,我找到了答案,我们必须在数据字段中设置content-available为1,否则,如果app处于背景。



现在通过 Google Firebase Console



我们必须分别使用(数据或通知或两者兼而有之)云计算的消息/ server.html#选择 rel =nofollow noreferrer> firebase服务器

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

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



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

  var admin = require(firebase-admin); 

var serviceAccount = require(pushnotificationapp-xxxxx.json); //这是从服务器生成的服务帐户详细信息

admin.initializeApp({
凭证:admin.credential.cert(serviceAccount),
databaseURL:https:// pushnotificationappxxxxx.firebaseio.com///你的数据库URL在这里。
});

var registrationToken =eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX .....; //设备的注册令牌
var payload = {
data:{
title:'Test Push',
message:'Push number 1' ,
info:超级秘密信息,
content-available:1//即使应用程序在后台也可以调用通知功能
}
};

发送通知或消息
admin.messaging()。sendToDevice(registrationToken,payload)
.then(function(response){
console.log (发送消息成功:,响应);
))
.catch(函数(错误){
console.log(Error sending message:,error);
});

更新

我也使用php服务器来实现。
这是我的工作php代码发送通知使用 HTTP POST 到FCM服务器 -

 <?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')

);

//即使您发送请求到https:// ...
$ options = array(
'http'=> array(
'header'=> array(Content-Type:application / json,
Authorization:key = AAAA1HfFM64:APA91XXXX ....),//这是服务器授权密钥您的Firebase项目中的项目设置选项卡
'method'=>'POST',
'content'=> json_encode($ data)

);

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

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


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

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

Here is my Code -

    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.

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?

解决方案

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.

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

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

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

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

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

UPDATE :

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;
}
?>

这篇关于在科尔多瓦背景Firebase推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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