使用带有 titanium appcelerator 的推送通知

Using Push notifications with titanium appcelerator

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

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

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

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

其实你做的是对的,但是推送通知背后有一个事实:

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

参见下面的代码片段:

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