In this tutorial, you will learn how to create a push notification from scratch using the Ionic Framework version 2.

If you are using the native plugin version 2.3, then visit the below link for working push notification code. Why because, this example code will work with native version 2.2 only.

https://ampersandacademy.com/tutorials/ionic-framework-version-2/push-notification-in-ionic-2-native-plugin-version-2-3-with-firebase-hosting-service-provider

First, create an ionic 2 project using

  ionic start pushapp blank --v2

 
Then add the android platform to the project using

  cd pushapp


  ionic platform add android


You need to install the push notification plugin to proceed further. To install a push notification plugin, you need sender id, which is issued by the google firebase (Push notification provider).

To get sender id, use the below link and log in with your Gmail.


https://console.firebase.google.com


Once you logged in, you can see create new project button. click the create new project button.

 

Give a name to your project and choose the country and click create the project.

Once the project created, click the project and click the settings.

Under the settings, you can find the cloud messaging tab. The cloud messaging tab displays the sender id and server key. copy the sender id.


Now you are ready to install the push notification plugin.  To install push notification use the below command with your sender id.

ionic plugin add phonegap-plugin-push --variable SENDER_ID=XXXXXXXXX --save

Note: Replace the XXXX with your sender id.

The save command saves the sender id in config.xml file in your project.

Then open your app.component.ts file and import Push, AlertController library using

import {Push} from "ionic-native";//for version 2.x native
import { Push, PushObject, PushOptions } from '@ionic-native/push';//version 3.native
import {AlertController} from "ionic-angular";


And create a constructor with Push and AlertController reference variable using

constructor(public  platform: Platform,public alertCtrl: AlertController)

Then create a new function, which is used to capture and display the push message from the firebase using the below code

initPushNotification(){
    if (!this.platform.is('cordova')) {
      console.warn("Push notifications not initialized. Cordova is not available - Run in physical device");
      return;
    }
    let push = Push.init({
      android: {
        senderID: "XXXXXXXXX"
      },
      ios: {
        alert: "true",
        badge: false,
        sound: "true"
      },
      windows: {}
    });

    push.on('registration', (data) => {
      console.log("device token ->", data.registrationId);
      //TODO - send device token to server
    });
    push.on('notification', (data) => {
      console.log('message', data.message);
      let self = this;
      //if user using app and push notification comes
      if (data.additionalData.foreground) {
        // if application open, show popup
        let confirmAlert = this.alertCtrl.create({
          title: 'New Notification',
          message: data.message,
          buttons: [{
            text: 'Ignore',
            role: 'cancel'
          }, {
            text: 'View',
            handler: () => {
              //TODO: Your logic here
              //self.nav.push(DetailsPage, {message: data.message});
            }
          }]
        });
        confirmAlert.present();
      } else {
        //if user NOT using app and push notification comes
        //TODO: Your logic on click of push notification directly
        //self.nav.push(DetailsPage, {message: data.message});
        console.log("Push notification clicked");
      }
    });
    push.on('error', (e) => {
      console.log(e.message);
    });
}

Replace your sender id with your sender id. And call this function inside your platform ready function using

this.initPushNotification();

 

The Complete app.component.ts code

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

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


import {Push} from "ionic-native";
import {AlertController} from "ionic-angular";
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage = HomePage;

  constructor(public  platform: Platform,public alertCtrl: AlertController) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
      this.initPushNotification();
    });
  }


  initPushNotification(){
    if (!this.platform.is('cordova')) {
      console.warn("Push notifications not initialized. Cordova is not available - Run in physical device");
      return;
    }
    let push = Push.init({
      android: {
        senderID: "210517257729"
      },
      ios: {
        alert: "true",
        badge: false,
        sound: "true"
      },
      windows: {}
    });

    push.on('registration', (data) => {
      console.log("device token ->", data.registrationId);
      //TODO - send device token to server
    });
    push.on('notification', (data) => {
      console.log('message', data.message);
      let self = this;
      //if user using app and push notification comes
      if (data.additionalData.foreground) {
        // if application open, show popup
        let confirmAlert = this.alertCtrl.create({
          title: 'New Notification',
          message: data.message,
          buttons: [{
            text: 'Ignore',
            role: 'cancel'
          }, {
            text: 'View',
            handler: () => {
              //TODO: Your logic here
              //self.nav.push(DetailsPage, {message: data.message});
            }
          }]
        });
        confirmAlert.present();
      } else {
        //if user NOT using app and push notification comes
        //TODO: Your logic on click of push notification directly
        //self.nav.push(DetailsPage, {message: data.message});
        console.log("Push notification clicked");
      }
    });
    push.on('error', (e) => {
      console.log(e.message);
    });
}

}

Now you are ready to make an apk. Generate android apk using

ionic build android

Now you have the apk file which will receive the push notification. Install this apk on your android phone.

Note: Enable install from unknown sources option in your phone. Or else the above-generated apk won't be installed on your phone.

Now go to firebase console. Click the notification. Click add android. Then add the push notification project name, which is available in your  
AndroidManifest.xml file, which is located at platforms\android folder of your project.

 

Click next and finish this step. Now you are ready to send a message to your mobile application.

To send a message, click the new message from the notification and choose your project name, fill the message and click the send message button.

 

The Notification looks like below