Android Code Setup

Android is set up the same way with just a few minor differences.  On Android, we use the ti.cloudpush module and ti.cloud for Push Notifications.  After registering with the server, the function should return a device token.  Save this device token in-app properties.

Example: Ti.App.Properties.setString(‘deviceToken’, e.deviceToken);

 However, make sure you set the application properties on the callback and not inside the common JS library.  These lib files can sometimes act strangely when it comes to saving app properties.

//require the notifications common js lib file
var notifications = require('notifications');
//check for a device token
var deviceToken = Ti.App.Properties.getString('deviceToken');

//check to see if deviceToken exists
if(deviceToken === '') {
	//get the devices token
	deviceToken = notifications.getToken();
	//set the deviceToken app property
	Ti.App.Properties.setString('deviceToken', deviceToken);
}

In the index js file we set up the device to look for a token and if there is not one to register the user for Push Notifications.

//require ti.cloudpush module
var CloudPush = require('ti.cloudpush');
//require ti.cloud module
var Cloud = require('ti.cloud');

//get device token
exports.getToken = function() {
  // Initialize the module
  CloudPush.retrieveDeviceToken({
      success: deviceTokenSuccess,
      error: deviceTokenError
  });
  // Enable push notifications for this device
  function deviceTokenSuccess(e) {
      CloudPush.enabled = true;
      return e.deviceToken;
  }
  function deviceTokenError(e) {
      alert('Failed to register for push notifications! ' + e.error);
  }
  // Process incoming push notifications
  CloudPush.addEventListener('callback', function (evt) {
      alert(evt.payload);
  });
};

The device token that is generated will allow the application to receive notifications.  You will be able to register the device with ‘Channels’.   The server can push information to certain Channels.  Say you want sports news.  Then a Channel called ‘sports_updates’ could be created.  Channels are not done server side.  Creation is done on the user side.  There is not a way to manually add a channel on the ACS Dashboard.  Once a user subscribes to a channel for the first time then it is created.

Subscribing a device token to a channel is a function in the common JS library you created for Push Notifications.  In this function, we pass two variables. One being the channel and the other being the device token that was generated earlier.  Each one is needed for the subscription.  Now the module ti.cloud will be required for this project as well.  The first module, ti.cloudpush, is just for registering a device token, and ti.cloud does the rest.  So we add ti.cloud to the notifications lib file.

//subscribe to a specific channel
exports.subscribe = function(channel, token) {
    Cloud.PushNotifications.subscribeToken({
        device_token: token,
        channel: channel
    }, function (e) {
        if (e.success) {
            alert('Subscribed');
        } else {
            alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
        }
    });
};

Subscribing a device token to a channel is a function in the common JS library you created for Push Notifications.  In this function, we pass two variables. One is the channel and the other being the device token that was generated earlier.  Each one is needed for the subscription.

You will also need to allow the user to unsubscribe from Channel based Pushed Notifications, which can be done using the unsubscribe function.

//unsubsribe from a specific channel
exports.unsubscribe = function(channel, token) {
    Cloud.PushNotifications.unsubscribeToken({
        device_token: token,
        channel: channel,
    }, function (e) {
        if (e.success) {
            alert('Unsubscribed');
        } else {
            alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
        }
    });
};

//device token
var deviceToken = Ti.App.Properties.getString('deviceToken');
//require notificiations lib file
var notifications = require('notifications');
//create view to house label and buttons
var container = Ti.UI.createView({
	width           : Ti.UI.FILL,
	height          : Ti.UI.FILL,
	top             : 30,
	layout          : 'vertical',
	backgroundColor : '#FFFFFF'
});
//create label for title
var channelLabel = Ti.UI.createLabel({
	width     : Ti.UI.FILL,
	height    : Ti.UI.SIZE,
	text      : 'Select a Channel',
	textAlign : 'center'
});
//create sports channel button
var sportsButton = Ti.UI.createButton({
	width     : Ti.UI.FILL,
	height    : Ti.UI.SIZE,
	top       : 10,
	title     : 'Sports'
});
//sports button event listener
sportsButton.addEventListener('click', function(e){
	if(deviceToken !== '') {
		notifications.subscribe('sports_updates', deviceToken);
	} else {
		alert('Error, device not registered for Push Notifications');
	}
});
//add elements together
container.add(channelLabel);
container.add(sportsButton);
$.win.add(container);

Now we need to create a sample page to test this all out with.  It will have a view, label, and button.  Clicking this button will subscribe the user to sports updates from the ACS server.

 This will create a basic view with a label and button on top of the window.  It will say ‘Sports’ and upon click will call the register function from the notifications lib file.

notifications.js

exports.userLogin = function() {
    // Log in to ACS
    Cloud.Users.login({
        login: 'push_notifications',
        password: 'pushy'
    }, function (e) {
        if (e.success) {
            alert('Login successful');
        } else {
            alert('Error:\n' +
                ((e.error && e.message) || JSON.stringify(e)));
        }
    });
};

You can also have users set up on the ACS server and log them in and subscribe to channels.  However, the user account must exist.  Generally, one user is created for the public, such as the ‘push_notifications’ user we see in the code.   This is perfect for just a basic app with notifications.  If you want user sessions and give the ability for people to create their own accounts you will have to look into Titanium.Cloud.Users on the documentation.

Sending Push Notifications using the Dashboard (http://dashboard.appcelerator.com)

This will cover three different ways for notifications to be sent.

Sending to Specific Channel/Users
Sending to All Channels
Setting up Recurring Notifications

Go to the Dashboard, then Cloud, then Push Notifications.  You will see a button that says ‘Send Push Notification’, click on it.

Sending to Specific Channel/Users

Let’s say we notify the ‘sports’ channel, then we need to choose ‘Specific Channel’ under the Channel.  Then under ‘Channel Name’ you would put ‘sports’.  The ACS server is Case Sensitive, so stick with lowercase or camel case.  For the ‘Alert’ section just come up with something such as ‘Richmond, Virginia to get a Major NFL Team’.  Under ‘Send When’ choose ‘Send Now’.  Then for ‘Title’ enter ‘WZYB Sports’ or something like that.

Click ‘Save Changes’ which will send the notification to the subscriber devices.

Sending to All Channels

Click ‘Save Changes’ which will send the notification to the subscriber devices.

Setting up Recurring Notifications

Click ‘Save Changes’ which will send the notification to the subscriber devices.

That concludes this tutorial on Push Notifications.  Please feel free to leave a comment and let us know if this worked for you.

Sign up for the Shockoe newsletter and we’ll keep you updated with the latest blogs, podcasts, and events focused on emerging mobile trends.