phonegap-plugin-push-tutorial
phonegap-plugin-push-tutorial
phonegap-plugin-push-tutorial

What is Push Notification ?

Push notifications are simple messages from apps installed on a device that wake up the handset and alert the user with a message displayed on the home or lock screen. Push notifications are widely used on all mobile devices as a way to inform or update the user.

!!! UPDATE !!! : Incase, If you want to use firebase for push notification (cordova-plugin-firebase) you can read this article https://codesundar.com/ionic-firebase-push-notification/

Top Push Notification Providers

You can also find some third party push notification providers such as Parse, PushWoosh (https://www.pushwoosh.com/), PushOver (https://pushover.net/) and more

How Push Notification works ?

how push notification works
how push notification works

 

Registration Process:

Step 1 : Mobile is Registered with GCM / APNS / MPNS

Step 2 : Once registration is successful, it’ll return some registrationID (encrypted) which is unique for every device and every application

Step 3 : After receiving RegistrationID, We have to submit the registrationID to our own server.

Step 4 : Store registrationID with our database with user’s unique ID

Sending Push Notification:

Step a : Send Push Message to GCM / APNS / MPNS with registrationID

Step b :  GCM / APNS / MPNS will automatically send your push messages when user is online

 

How to send push Notification using Phonegap / Apache Cordova ?

  1. Creating a Google Project
  2. Working with Mobile for receiving Push Notification
  3. Working with PHP for Sending Push Notification

Creating a new Google Project

login-with-google-account
login-with-google-account

 

  • Create New Project from your dashboard
create-new-google-project
create-new-google-project

 

3. Add a Project Name ( you can choose anything you want)

type-project-name
type-project-name

 

4. Copy the sender ID, here the Sender ID is 721393051486 ( please do not use this ID, may not work)

copy-sender-id

5. For Enabling GCM for a project,

  • Choose API
  • Search “cloud messaging”
  • Click Google Messaging for android
enable-gcm
enable-gcm

6. Click Enable API

enable-gcm-1

7. For Creating Server Key ( which is used for sending Push notification using PHP)

  • Click Credential from your left menu
  • Click Add credential button
  • Click API key, it will open a new popup window for creating server key
  • Click Next, you can get Server key

choose-credential

choose-server-key
choose-server-key
create-server-key
create-server-key
copy-server-key
copy-server-key

 Setting up Apache Cordova / Phonegap Project for Receiving Push Notifications

In this tutorial we’ll see how to setup Apache Cordova / Phonegap project for receiving push notifications.

  • Open Android SDK Manager (type android in terminal)
  • Make sure you’ve installed the required tools

sdk-manager-tools

Receiving Push Notification using Phonegap / Apache Cordova

  1. Create a New Project or use existing project
  2. Add platform such as android
  3. Add you Push Notification Plugin (https://github.com/phonegap/phonegap-plugin-push)
cordova plugin add phonegap-plugin-push --variable SENDER_ID="721393051486"

Apache Cordova / Phonegap Push Notification Example Code.

replace "senderID": "721393051486" with your own sender ID

var push = PushNotification.init({ "android": {"senderID": "721393051486"},
         "ios": {"alert": "true", "badge": "true", "sound": "true"}, "windows": {} } );

    push.on('registration', function(data) {
        // data.registrationId
    });

    push.on('notification', function(data) {
        // data.message,
        // data.title,
        // data.count,
        // data.sound,
        // data.image,
        // data.additionalData
    });

    push.on('error', function(e) {
        // e.message
    });

During Initiation

when GCM registration is success, you’ll receive GCM registration ID with has 256 char encrypted data by using data.registrationId. registrationId is an unique for all device & all application

While receiving Push Notification 

when you send Push Message from server, push.on('notification' will be called. you can receive these data such as message, title, count, sounds, image, additionalData. if some error occurred it’ll initiate push.on('error'

Apache Cordova / Phonegap Push Notification Full Example code

<!DOCTYPE html>
<html>
<head>
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<title>Hello World</title>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
 var push = PushNotification.init({ "android": {"senderID": "YOUR_SENDER_ID"}});
 push.on('registration', function(data) {
 console.log(data.registrationId);
 document.getElementById("gcm_id").innerHTML = data.registrationId;
 });

 push.on('notification', function(data) {
 alert(data.title+" Message: " +data.message);
 });

 push.on('error', function(e) {
 alert(e);
 });
}
</script>
</head>
<body>
<h1>Push Notification Example</h1>
Your GCM ID : <br/>
<p id="gcm_id"></p>
</body>
</html>

Compile this application and run on your device, you can see some Registration ID (256 char encrypted). i.e, your GCM ID like

APA91bFIj2WLkD3W4kbZcGO7dyI-TKKX0QpYCwtzqE2cNC0GbnUfQ7_gvQKOUloSb9T-6OZMxKdHXj8biiMYVgRJJP-C6b3PfpC7Kzu4G77PqMeGekHU9W6qTwnu0YTtWGNd6tGMBQka

Apache Cordova / Phonegap Push Notification is not working ?

  • Check whether you’ve installed Push Notification Plugin
  • Make sure, you’ve installed required tools in SDK Manager (see the above figure)
  • Check you’ve included cordova.js file with your project
  • Check your Sender ID which you’re created in GCM Projects
  • Make sure your internet connection

 

Sending Push Notification using PHP for Phonegap / Apache Cordova Projects

Requirements:

  • Install some local server (XAMPP / WAMP / MAMP ) for running your PHP files.
  • Make sure, you’ve enabled CURL

<?php
$to="APA91bFIj2WLkD3W4kbZcGO7dyI-TKKX0QpYCwtzqE2cNC0GbnUfQ7_gvQKOUloSb9T-6OZMxKdHXj8biiMYVgRJJP-C6b3PfpC7Kzu4G77PqMeGekHU9W6qTwnu0YTtWGNd6tGMBQka";
$title="Push Notification Title";
$message="Push Notification Message";
sendPush($to,$title,$message);

function sendPush($to,$title,$message)
{
// API access key from Google API's Console
// replace API
define( 'API_ACCESS_KEY', 'AIzaSyC_LcqN85irttxFXcNIzkrSkPhAfcu68HI');
$registrationIds = array($to);
$msg = array
(
'message' => $message,
'title' => $title,
'vibrate' => 1,
'sound' => 1

// you can also add images, additionalData
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
}
?>

Note :

  • Change $to=APA91bFIj2WLkD3W4kbZcGO7dyI..... with your registration ID
  • Change define( 'API_ACCESS_KEY', 'AIzaSyC_LcqN85irttxFXcNIzkrSkPhAfcu68HI'); with your Server key

 

Now Run your PHP file on your server. you’ll receive a message. when you open the message you can see the same message and title in alert box (you can customize them)

Sundaravel M

About the author: Hey! It's me sundar. (Yea, I'm the founder of codesundar.com). I'm a passionate computer programmer who loves modern web and mobile development. feel free to reach me : Facebook - Twitter - Google+