Front-End Web & Mobile

Push Notifications with Ionic and Amazon Pinpoint

Engaging your customers through communication channels such as push notifications is important for mobile app success. AWS services such as AWS Mobile Hub and Amazon Pinpoint enable you to do this in a scalable and cost effective manner. When using these services with development tooling like Ionic Framework you can rapidly develop modern applications to build your business.

Ionic recently announced that they are sunsetting their Push and Auth services. We recently launched an Ionic Starter Project and posted a tutorial for adding sign-up and sign-in to an Ionic project to help customers evaluate AWS as an alternative for migration. In this post, we cover how to add push notifications to your Ionic project with Amazon Pinpoint.

In this tutorial, we show how to add push notifications with Google Cloud Messaging (GCM). A similar procedure can be followed for Apple Push Notification service (APNs) which you can find on the Apple Developer website.

Enable Google Cloud Messaging

Open a web browser and navigate to https://console.cloud.google.com/home/.

  1. Open an existing project or create a new one.
  2. Select IAM and admin on the left.
  3. Click Settings and note the Project Number.
  4. In the Search Bar at the top of the screen, type Cloud Messaging and click it.
  5. Select the Credentials section on the left.
  6. Click Create Credentials, select API key and save this for later.

You should now have a Project Number and API key that you can use in the following sections.

Create Ionic Project

Now you can create an Ionic project and add plugins for push notifications. In the following example, use the Project Number from the previous procedure as the value for SENDER_ID:

npm install –g ionic
ionic start pinpoint blank
cd pinpoint
npm install --save @ionic-native/push--save
cordova plugin add phonegap-plugin-push --variable SENDER_ID=<YOUR GCM Project Number> --save

Modify Ionic project for push notifications

This tutorial provides basic steps to follow for your application to use Amazon Pinpoint push notifications. You will need:

  1. The Registration ID for the Android device to send push notifications to via GCM.
  2. An action to perform after a push notification is received.

For this sample, we log the Registration ID to the console and then pop up an alert when a push notification is received. You can find more information on this process in the Ionic documentation.

First, in the pinpoint folder created from the CLI command, edit ./src/app/app.module.ts to have Push listed under providers:

providers: [
    StatusBar,
    SplashScreen,
    Push,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]

Next, edit ./src/app/app.component.ts to have imports for Push, PushObject, and PushOptions from ionic-native/push. You also need two functions: a function to get the device token from GCM when the app starts, and a function to pop up a notification when a push is received. For brevity, the following code is below. NOTE that you must update the SenderID in the following example with the ProjectID from earlier:

import { Component } from '@angular/core';
import { Platform, Nav, AlertController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';

import { Push, PushObject, PushOptions } from '@ionic-native/push';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

  constructor(platform: Platform, 
              statusBar: StatusBar, 
              splashScreen: SplashScreen,
              public push: Push,
              public alertCtrl: AlertController) {
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
      this.initPushNotification();

    });
  }

  initPushNotification(){

  const options: PushOptions = {
    android: {
      senderID: "YOUR_GCM_PROJECT_ID"
    }
  };

  const pushObject: PushObject = this.push.init(options);

    pushObject.on('registration').subscribe((data: any) => {
      console.log("device token:", data.registrationId);

      let alert = this.alertCtrl.create({
                  title: 'device token',
                  subTitle: data.registrationId,
                  buttons: ['OK']
                });
                alert.present();

    });

    pushObject.on('notification').subscribe((data: any) => {
      console.log('message', data.message);
      if (data.additionalData.foreground) {
        let confirmAlert = this.alertCtrl.create({
          title: 'New Notification',
          message: data.message,
          buttons: [{
            text: 'Ignore',
            role: 'cancel'
          }, {
            text: 'View',
            handler: () => {
              //TODO: Your logic here
            }
          }]
        });
        confirmAlert.present();
      } else {
      let alert = this.alertCtrl.create({
                  title: 'clicked on',
                  subTitle: "you clicked on the notification!",
                 buttons: ['OK']
                });
                alert.present();
        console.log("Push notification clicked");
      }
   });

    pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
  }
}

Save your code and run the Android application.

Enable and send push notifications with Amazon Pinpoint and AWS Mobile Hub

To test your application with Amazon Pinpoint, first create an AWS Mobile Hub project from the console.

  1. Navigate to https://console.aws.amazon.com/mobilehub.
  2. Create a project with a unique name.
  3. Select Messaging and Analytics, click Messaging, and then click Mobile Push.
  4. Click Android and then enter your API Key and Sender ID as appropriate (remember – Sender ID is the Project Number from the GCM console).
  5. Click Enable.
  6. On the left side of the Mobile Hub console, click Engage. This opens the Amazon Pinpoint console.
  7. Click Direct on the left side of the page and you see a Mobile Push tab. Keep this open.

Go back to your running Ionic application and use adb from the command line or in Android Studio, the Registration ID should display on the screen as device token. You can launch this on an emulator with one step, using the Ionic CLI:

ionic cordova emulate android --l -c -s

If everything is working you should see a token like the following:

["device token:","e4nGb_9sdpw:APA91bEgWaDsdfs8adyfds8a78f7sad8f7asd8Su_8UoonSNO7kx5LxlnNuoIt345GU9piBthbjit-NeFNDCsDCoQezezy-asdjfkasdh9dfd8ds8fas81MUSGZrcj_hd5RG"]}

Copy this token and paste it in the Amazon Pinpoint console in the section called Endpoint IDs. Then, at the bottom of the page, type a Title and Message, and then press Sent. If successful, there is a New Notification message on the phone.

Note: Emulators don’t always work for push notifications. You may need to restart the emulator or use a physical phone

Next Steps

Please let us know which additional features or tutorials for using AWS and Ionic technologies together you are interested in. You can leave us comments here or on the GitHub repo.