Background Firebase Push Notifications in Cordova

孤人 提交于 2019-11-28 02:12:03

问题


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?


回答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.

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



回答2:


i was going through the same issue but i added "content-available": '1' also but my phone was not receiving any background push.

Finally i found that it was issue with my phone as mentioned here: https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#huawei-and-xiaomi-phones

Huawei and Xiaomi Phones

These phones have a particular quirk that when the app is force closed that you will no longer be able to receive notifications until the app is restarted. In order for you to receive background notifications:

On your Huawei device go to Settings > Protected apps > check "My App" where. On your Xiaomi make sure your phone has the "Auto-start" property enabled for your app. On your Asus make sure your phone has the "Auto-start" property enabled for your app.

Hope it will help someone.



来源:https://stackoverflow.com/questions/44368640/background-firebase-push-notifications-in-cordova

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!