Search code examples
appceleratorappcelerator-mobileappcelerator-titanium

Using Push notifications with titanium appcelerator


I am using Titanium's push notification functionality with alloy for Android and iOS. I am initializing push notification subscription from alloy.js, i.e. basically calling CloudPush's retrieveDeviceToken method to get a device token and then

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

The challenge is that, alloy.js gets called everytime I will restart the app. That means a new device token is generated and channel is subscribed again and again on every restart of app.

I am wondering if this is the right way to use the push subscription. Is there a way to avoid these multiple subscriptions from the same device.


Solution

  • Actually you are doing the right thing, but there is a fact behind Push Notifications:

    • You will always get a single device token no matter how many times you call CloudPush.retrieveDeviceToken() method.
    • Device Token will only differ when you will uninstall the app and install it again.
    • So all you need to do to avoid the subscription to channel multiple times is that Save the device token in Ti.App.Properties and then check for this property whether it has a value or not.

    See below code snippet:

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