首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只有当PhoneGap应用程序在前台使用节点推送通知时,Android中的推送通知才能工作。

只有当PhoneGap应用程序在前台使用节点推送通知时,Android中的推送通知才能工作。
EN

Stack Overflow用户
提问于 2020-07-29 08:01:02
回答 1查看 914关注 0票数 0

在我的PhoneGap / Cordova应用程序(使用Framework7)中,我使用<plugin name="phonegap-plugin-push" source="npm" spec="2.3.0" />来启用推送通知。在项目文件夹的根目录中,我已经将google-services.json文件放入其中。当用户登录到我的应用程序时,设备令牌将在我的服务器上注册。接下来,我使用node-pushnotifications模块向这些令牌发送推送通知。

对于iOS设备,一切正常工作,但安卓只有在应用程序处于前台时才能工作。当我发送推送通知时,应用程序在后台,似乎什么都没有发生。当应用程序被打开(带回前台)时,会显示丢失的通知(更准确地说,弹出消息显示“新消息已经到达”,对于每个“遗漏”的推送通知,就像应用程序处于前景模式时的预期行为一样)。

我在StackOverflow上找到了几个相关的问题和答案,但它们并没有解决我的问题,但也许我在这些答案中遗漏了什么?例如,有人建议您需要指定一个message变量。但是,当我在服务器代码中包含这一点时,就会出现一个解析错误。另外,根据我阅读的node-pushnotifications模块的说明,这应该是不必要的。

===

更新1

当我使用Firebase控制台向Android设备发送推送消息时,一切正常工作(当应用程序处于后台时,将显示推送消息)。我怀疑原因在于node-pushnotifications模块。

到目前为止,我在模块设置中尝试了,我有:

  1. icon设置为默认值;
  2. sound设置为默认值;
  3. ID设置为SenderID (导致失败->通知未发送);H 222H 123Set phonegapphonegap(导致失败->通知未发送)H 226G 227

===

更新2

当应用程序处于后台时(但当应用程序关闭时),使用node-gcm模块正确地传递推送通知。

===

欢迎使用node-pushnotifications进行此工作的任何帮助。我很高兴在需要的时候给出更多的解释和细节。

应用程序中的代码

基于http://macdonst.github.io/push-workshop/提供的代码

请注意。对于SenderID,我使用在/by Firebase中生成的发送者id键。

代码语言:javascript
复制
var message = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.getElementById("toggleBtn").addEventListener('click', this.toggle, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
      message.push = PushNotification.init({
           "android": {
             "senderID": "**********"
           },
           "ios": {
             "sound": true,
             "vibration": true,
             "badge": false
           },
           "windows": {}
       });

       message.push.on('registration', function(data) {
           var oldRegId = localStorage.getItem('registrationId');
           if (oldRegId !== data.registrationId) {
               // Save new registration ID
               localStorage.setItem('registrationId', data.registrationId);
               // Post registrationId to your app server as the value has changed
               var uname= window.localStorage.getItem('uname');
               var pwd= window.localStorage.getItem('pwd');
               var devicetoken=localStorage.getItem('registrationId');
               
               var dataString="uname="+uname+"&pwd="+pwd+"&devicetoken="+devicetoken+"&updateregistration=yes";
            
                $.ajax({
                    type:"POST",  
                    url:"******************", data: dataString,
                    crossDomain: true,
                    cache: false, 
                    success:function(data)  
                    {  
                    }  
                });  
   
           }
       });

       message.push.on('error', function(e) {
           console.log("push error = " + e.message);
       });

        message.push.on('notification', function(data) {
          console.log('notification event');
            
          app.dialog.alert("You have a new message", function () {
              
                        app.views.main.router.navigate('/messages/');

            });
        
        });
    }
};

message.initialize();

服务器上的代码

基于https://github.com/appfeel/node-pushnotifications提供的代码

请注意。对于gcm id,我使用在/by Firebase中生成的服务器密钥。

代码语言:javascript
复制
// Step 1: configure push notification settings
var PushNotifications = require('node-pushnotifications')

const settings = {
    gcm: {
       id: '*******',
       phonegap: true, // phonegap compatibility mode, see below (defaults to false)
    },
    apn: {
       token: {
            key: '*******', // optionally: fs.readFileSync('./certs/key.p8')
            keyId: '*******',
            teamId: '*******',
        },
        production: true // true for APN production environment, false for APN sandbox environment,
        //...
    },
    isAlwaysUseFCM: false, // true all messages will be sent through node-gcm (which actually uses FCM)
};
const push = new PushNotifications(settings);

// Step 2 create the notification
const data = {
    title: 'New push notification', // REQUIRED for Android
    topic: '**********', // REQUIRED for iOS (apn and gcm)
    /* The topic of the notification. When using token-based authentication, specify the bundle ID of the app.
     * When using certificate-based authentication, the topic is usually your app's bundle ID.
     * More details can be found under https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns
     */
    body: 'Powered by AppFeel',
    custom: {
        sender: 'AppFeel',
    },
    priority: 'high', // gcm, apn. Supported values are 'high' or 'normal' (gcm). Will be translated to 10 and 5 for apn. Defaults to 'high'
    collapseKey: '', // gcm for android, used as collapseId in apn
    contentAvailable: true, // gcm, apn. node-apn will translate true to 1 as required by apn.
    delayWhileIdle: true, // gcm for android
    restrictedPackageName: '', // gcm for android
    dryRun: false, // gcm for android
    icon: '', // gcm for android
    image: '', // gcm for android
    style: '', // gcm for android
    picture: '', // gcm for android
    tag: '', // gcm for android
    color: '', // gcm for android
    clickAction: '', // gcm for android. In ios, category will be used if not supplied
    locKey: '', // gcm, apn
    locArgs: '', // gcm, apn
    titleLocKey: '', // gcm, apn
    titleLocArgs: '', // gcm, apn
    retries: 1, // gcm, apn
    encoding: '', // apn
    badge: 2, // gcm for ios, apn
    sound: 'ping.aiff', // gcm, apn
    android_channel_id: '', // gcm - Android Channel ID
    notificationCount: 0, // fcm for android. badge can be used for both fcm and apn
    alert: { // apn, will take precedence over title and body
        title: 'title',
        body: 'body'
        // details: https://github.com/node-apn/node-apn/blob/master/doc/notification.markdown#convenience-setters
    },
    silent: false, // apn, will override badge, sound, alert and priority if set to true
    /*
     * A string is also accepted as a payload for alert
     * Your notification won't appear on ios if alert is empty object
     * If alert is an empty string the regular 'title' and 'body' will show in Notification
     */
    // alert: '',
    launchImage: '', // apn and gcm for ios
    action: '', // apn and gcm for ios
    category: '', // apn and gcm for ios
    // mdm: '', // apn and gcm for ios. Use this to send Mobile Device Management commands.
    // https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/MobileDeviceManagementProtocolRef/3-MDM_Protocol/MDM_Protocol.html
    urlArgs: '', // apn and gcm for ios
    truncateAtWordEnd: true, // apn and gcm for ios
    mutableContent: 0, // apn
    threadId: '', // apn
    pushType: undefined, // apn. valid values are 'alert' and 'background' (https://github.com/parse-community/node-apn/blob/master/doc/notification.markdown#notificationpushtype)
    expiry: Math.floor(Date.now() / 1000) + 28 * 86400, // unit is seconds. if both expiry and timeToLive are given, expiry will take precedence
    timeToLive: 28 * 86400,
    headers: [], // wns
    launch: '', // wns
    duration: '', // wns
    consolidationKey: 'my notification', // ADM
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-26 00:43:31

--这是我实现的解决方案(目前正在安卓10和iOS 13.6上运行和测试)

它可以帮助您轻松显示定制推送通知的背景,前景,何时使用,当手机被锁定。

My配置在CLI:

代码语言:javascript
复制
cordova -v

7.1.0

代码语言:javascript
复制
cordova platforms

android 8.0.0

ios 4.5.5

代码语言:javascript
复制
cordova plugins

phonegap-插件-推2.3.0 "PushPlugin“

phonegap-插件-Multidex 1.0.0 "Multidex“

我正在使用的JS应用程序代码

代码语言:javascript
复制
document.addEventListener("deviceready", registrarDevice, false);

function registrarDevice() {
    try {
        var push = PushNotification.init({
            android: {
                senderID: "YOUR_SENDER_ID_FROM_FIREBASE"
            },
            browser: {
                pushServiceURL: 'http://push.api.phonegap.com/v1/push'
            },
            ios: {
                alert: "true",
                badge: "true",
                sound: "true"
            },
            windows: {}
        });

        push.on('registration', function (data) {
            // data.registrationId
            console.log(data);
        });

        push.on('notification', function (data) {
            console.log(data);
            // data.message,
            // data.title,
            // data.count,
            // data.sound,
            // data.image,
            // data.additionalData
        });

        push.on('error', function (e) {
            // e.message
            console.log(e);
        });
    } catch (err) {
        console.log("Error registrarDevice: ", err.message);
    }
}

在我的服务器上的PHP代码

代码语言:javascript
复制
class FCM {
    function __construct() {
    }

    public function send_push_notification($registatoin_ids, $notification, $device_type) {
        $url = 'https://fcm.googleapis.com/fcm/send';
        if($device_type == "Android"){
            $fields = array(
                'to' => $registatoin_ids,
                'data' => $notification
            );
        } else {
            $fields = array(
                'to' => $registatoin_ids,
                'notification' => $notification
            );
        }
        // Your Firebase Server API Key
        $apikey = "YOUR_FIREBASE_SERVER_API_KEY";
        $headers = array('Authorization:key='.$apikey,'Content-Type:application/json');
        // Open curl connection
        $ch = curl_init();
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        curl_close($ch);
    }
}   


function notificaciones_android_base($xdevice_destino,$xtitulo,$xtexto){
    $NotificationArray= array();                                                        
    $NotificationArray["body"] = $xtexto;
    $NotificationArray["title"] = $xtitulo;
    $NotificationArray["sound"] = "default";
    $NotificationArray["type"] = 1;

    $fcm = new FCM();
    $retresult = $fcm->send_push_notification($xdevice_destino, $NotificationArray, "Android");

    return $retresult;
}


$info_test="Greetings folks!, Testing de push message :-)";
echo "<br>".notificaciones_android_base("YOUR_DEVICE_ID","NotificationTitle2021",$info_test);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63148989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档