【问题标题】:Using Push notifications with titanium appcelerator将推送通知与钛加速器一起使用
【发布时间】:2016-06-02 15:25:51
【问题描述】:

我正在使用 Titanium 的推送通知功能和适用于 Android 和 iOS 的合金。我正在从alloy.js 初始化推送通知订阅,即基本上调用CloudPush 的retrieveDeviceToken 方法来获取设备令牌,然后

 Cloud.PushNotifications.subscribe({
    channel : _channel,
    device_token : _token,
    type : OS_IOS ? 'ios' : 'android'
  }, function(_event) {..}

挑战在于,每次我重新启动应用程序时都会调用alloy.js。这意味着每次重新启动应用程序时都会生成一个新的设备令牌并一次又一次地订阅频道。

我想知道这是否是使用推送订阅的正确方法。有没有办法避免来自同一设备的多个订阅。

【问题讨论】:

    标签: appcelerator appcelerator-mobile appcelerator-titanium


    【解决方案1】:

    其实你在做正确的事,但推送通知背后有一个事实:

    • 无论您调用 CloudPush.retrieveDeviceToken() 方法多少次,您都将始终获得一个设备令牌。
    • 只有在您卸载应用并重新安装时,设备令牌才会有所不同。
    • 因此,为了避免多次订阅频道,您只需将设备令牌保存在 Ti.App.Properties 中,然后检查该属性是否有值。

    见下面代码sn-p:

    var CloudPush = require('ti.cloudpush');
    
                if ( CloudPush.isGooglePlayServicesAvailable() ) {
                    CloudPush.retrieveDeviceToken({
                        success : tokenSuccess,
                        error : tokenError
                    });
    
                    // Process incoming push notifications
                    CloudPush.addEventListener('callback', pushRecieve);
    
                } else {
                    alert("Please enable Google Play Services to register for notifications.");
                }
    
    // Save the device token for subsequent API calls
    function tokenSuccess(e) {
        var previousToken = Ti.App.Properties.getString("DEVICE_TOKEN", "");
    
        var newToken = "" + e.deviceToken;
        Ti.API.info('** New Device Token = ' + newToken);
    
        if (newToken !== previousToken) {
            Ti.App.Properties.setString("DEVICE_TOKEN", newToken);  
    
            var Cloud = require("ti.cloud");
    
            Cloud.PushNotifications.subscribe({
                channel : _channel,
                device_token : newToken,
                type : OS_IOS ? 'ios' : 'android'
            }, function(_event) {});
        }
    }
    
    
    function tokenError(e) {
        alert('Failed to register for push notifications.');
    }
    

    【讨论】:

    • 你可能甚至不需要存储令牌;您可以只为您的频道存储订阅状态(真/假)。正如您所说,设备令牌只会在您卸载/重新安装应用程序时更改。如果您卸载,您存储的应用程序属性将被销毁。因此,您唯一一次进入 (newToken !== previousToken) 条件是在您第一次运行应用程序时。在 subscribe() 调用的成功回调中记录订阅可能会更好。因此,如果您由于某种原因未能订阅,您可以在下次发布时重试。
    • "只有当您卸载应用程序并重新安装时,设备令牌才会有所不同。"我试图卸载并重新安装应用程序。这使得同一个设备注册了两次。而且我收到重复的推送通知。如何避免这种情况?还是因为我的应用未处于生产模式而发生这种情况。
    • @Kamal 我也面临这个问题。有什么解决办法吗?
    猜你喜欢
    • 1970-01-01
    • 2015-07-12
    • 2012-04-05
    • 2016-11-06
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多