Android (GCM) Push Notification Tutorial – Part 1

In this tutorial, I will show you how to implement push notifications in your native app for android.

Download the required software packages.

  1. Download and install Android Studio and Android SDK.
  2. Android Studio + SDK – http://developer.android.com/sdk/index.html.

Setting up your development environment

Open your Android Studio and choose Start a new Android Studio project.

Start a new Android Studio project

Start a new Android Studio project

Enter your custom Application name, Company Domain and select Project location. Click Next.

Configure your new project.

Configure your new project.

Select Phone and Tablet. Make sure API 15 selected. Click Next.

Configure your new project.

Configure your new project.

Select Blank Activity and click Next.

Add an activity to Mobile.

Add an activity to Mobile.

Click Finish.

Customize the activity.

Customize the activity.

Now we need to get project id from google cloud. Go to  https://console.developers.google.com and create a new project. Click Create Project button and a popup will appear. Enter your project name and click Create. Mine is Native Push.

google cloud create project

google cloud create project

Then you will be direct to this page. Copy out your project number on the top. Click Enable API. Enable Google Cloud Messaging for Android. Click Credentials under APIs and auth on left sidebar.

google developer console API

google developer console API

 

Google Cloud Messaging for Android

Google Cloud Messaging for Android

Go to Credentials page. It’s under APIs & authCredentials.

APIs Credentials

APIs Credentials

Choose Server key.

APIs Credentials - server key

APIs Credentials – server key

Enter your custom Name and click Create.

APIs Credentials - Create server API key

APIs Credentials – Create server API key

Below is API key details for your project. Copy your API key.

APIs Credentials - API keys

APIs Credentials – API keys

Continue…

Implement Push Notifications for android and iOS (phonegap) – part 1

In this tutorial I will show you how to implement push notifications in your phonegap app (cordova) for android and iOS platform.

Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users’ Android-powered device, and also to receive messages from devices on the same connection. The GCM service handles all aspects of queueing of messages and delivery to the target Android application running on the target device. GCM is completely free no matter how big your messaging needs are, and there are no quotas. Reference.

Google Cloud Messaging (GCM)

Google Cloud Messaging (GCM)

Apple Push Notification service (APNs for short) is the centrepiece of the push notifications feature. It is a robust and highly efficient service for propagating information to iOS and OS X devices. Each device establishes an accredited and encrypted IP connection with the service and receives notifications over this persistent connection. If a notification for an application arrives when that application is not running, the device alerts the user that the application has data waiting for it. Reference.

Apple Push Notifications Service (APNS)

Apple Push Notifications Service (APNS)

For this tutorial, we will using ionic framework to create the app. Open your terminal (mac), cmd (windows) . Create an app using this command,

ionic start com.revivalx.ionic.push blank
ionic framework

ionic framework

Install PushPlugin phonegap plugin into your project.

cd com.revivalx.ionic.push blank
cordova plugin add https://github.com/phonegap-build/PushPlugin
PushPlugin phonegap plugin

PushPlugin phonegap plugin

Open your config.xml and change it to like this.

ionic directory

ionic directory

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.revivalx.ionic.push" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>IonicPush</name>
    <description>
        IonicPush.
    </description>
    <author email="mohammadnrdn@gmail.com" href="http://revivalx.com/">
      Mohammad Nurdin bin Norazan
    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />

    <!-- Don't store local date in an iCloud backup. Turn this to "cloud" to enable storage
         to be sent to iCloud. Note: enabling this could result in Apple rejecting your app.
    -->
    <preference name="BackupWebStorage" value="none" />

    <feature name="StatusBar">
      <param name="ios-package" value="CDVStatusBar" onload="true" />
    </feature>
</widget>

For Android.

Now we need to get project id from google cloud. Go to  https://console.developers.google.com and create a new project. Click Create Project button and a popup will appear. Enter your project name and click Create. Mine is Ionic Push.

google cloud create project

google cloud create project

Then you will be direct to this page. Copy out your project number on the top. Click Enable API.

google cloud developer dashboard

google cloud developer dashboard

Enable Google Cloud Messaging for Android. Click Credentials under APIs and auth on left sidebar.

google developer console API

google developer console API

Create new key under Public API access.

APIs and auth

APIs and auth

Click Server key.

server key

server key

Leave it blank and click Create.

server key

server key

Below is API key details for your project. Copy your API key.

API key

API key

So next tutorial is for iOS part. http://blog.revivalx.com/2014/08/29/implement-push-notifications-for-android-and-ios-phonegap-part-2/

 

 

 

 

Push Notification Phonegap Plugin for Android and iOS – Part 1

Push notification is describes a style of Internet-based communication where the request for a given transaction is initiated by the publisher or central server. It is contrasted with pull, where the request for the transmission of information is initiated by the receiver or client (Wikipedia).

There are two types of push notification service that mostly popular among the others are android and iOS. I’m not sure about blackberry and windows mobile because currently doing only for iOS and android platform.

Push notification for iOS called APNs stands for Apple Push Notification Service. For android called GCM stands for Google Cloud Messaging. You can find more details about both of these services at their official site.

APNs

APNs

GCM

GCM

Last month I already attend worklight training located at Plaza IBM, One Utama organised by IBM. I already post an article about this training details here.

http://blog.revivalx.com/2014/02/18/ibm-worklight-training-day-2/

Besides that, you can find more details about APNs and GCM from third party links.

APNs

  1. http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1
  2. http://devgirl.org/2012/10/19/tutorial-apple-push-notifications-with-phonegap-part-1/

GCM

  1. http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

Ok, enough chit chat. Now, I want to share with you how to do push notification phonegap plugin for android platform. First, you need to create cordova project. Make sure you have eclipse Juno and Xcode (for mac users).

cordova create project

cordova create project

Open up your config.xml in your project then edit project id and name.

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.revivalx.PushNotification" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>PushNotification</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>

Go to your project directory then add these two platforms into your cordova project, iOS and android.

Run this command in your terminal.

cordova platform add android
cordova platform add ios
android

android

iOS

iOS

Create a new project in eclipse.

eclipse new project

eclipse new project 1

eclipse new project 2

eclipse new project 2

eclipse new project 3

eclipse new project 3

Make sure your project hierarchy look like this one.

Download this phonegap plugin and install into your cordova project.

https://github.com/phonegap-build/PushPlugin

https://github.com/apache/cordova-plugin-console

Run this command to install this plugin into your project.

cordova plugin add https://github.com/phonegap-build/PushPlugin
cordova plugin add https://github.com/apache/cordova-plugin-console
cordova plugin

cordova plugin

To make your push notifications works, you need to register your app first in google cloud (android) and apple developer (iOS).  For android part, you need project id for push notification recognise your device. Otherwise, it won’t work. You can refer this tutorial how to register your app.

iOS: http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1

Android: http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

Below are websites that you need to register your app for push notification.

Google Cloud: https://cloud.google.com

Apple Developer: https://developer.apple.com/

After you finish registered your app, go back to your eclipse and insert this script into your index.html .

https://github.com/phonegap-build/PushPlugin/blob/master/www/PushNotification.js

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
<script src="js/PushNotification.js"></script>
<script>
var pushNotification;

function onDeviceReady() {
pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android') {
console.log("registering android");
pushNotification.register(successHandler, errorHandler, {
"senderID": "xxxxxxxxxxx",
"ecb": "onNotificationGCM"
}); // required!
} else {
console.log("registering iOS");
pushNotification.register(tokenHandler, errorHandler, {
"badge": "true",
"sound": "true",
"alert": "true",
"ecb": "onNotificationAPN"
}); // required!
}
}
// handle APNS notifications for iOS

function onNotificationAPN(e) {
if (e.alert) {
navigator.notification.alert(e.alert);
}
if (e.sound) {
var snd = new Media(e.sound);
snd.play();
}
if (e.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
}
}
// handle GCM notifications for Android

function onNotificationGCM(e) {
navigator.notification.alert(e.event);
switch (e.event) {
case 'registered':
if (e.regid.length > 0) {
navigator.notification.alert(e.regid);
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
console.log("regID = " + e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (e.foreground) {
navigator.notification.alert('--INLINE NOTIFICATION--');
// if the notification contains a soundname, play it.
var my_media = new Media("/android_asset/www/" + e.soundname);
my_media.play();
} else { // otherwise we were launched because the user touched a notification in the notification tray.
if (e.coldstart) navigator.notification.alert('--COLDSTART NOTIFICATION--');
else navigator.notification.alert('--BACKGROUND NOTIFICATION--');
}
navigator.notification.alert(e.payload.message);
navigator.notification.alert('MESSAGE -> MSGCNT: ' + e.payload.msgcnt);
break;
case 'error':
navigator.notification.alert('ERROR -> MSG:' + e.msg);
break;
default:
navigator.notification.alert('EVENT -> Unknown, an event was received and we do not know what it is');
break;
}
}

function tokenHandler(result) {
navigator.notification.alert(result, null, 'Alert', 'OK');
sessionStorage.setItem("deviceId", result);
sessionStorage.setItem("notificationServer", "APNS");
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.
}

function successHandler(result) {
navigator.notification.alert(result, null, 'Alert', 'OK');
sessionStorage.setItem("deviceId", result);
sessionStorage.setItem("notificationServer", "GCM");
}

function errorHandler(error) {
navigator.notification.alert(error, null, 'Alert', 'OK');
}
document.addEventListener('deviceready', onDeviceReady, true);
</script>
</head>
<body>
<div class="app">
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>

Then build your project. Run these command in your terminal.

cordova build ios
cordova build android
cordova build ios

cordova build ios

cordova build android

cordova build android

I will continue on the second part about how to test your push notification for android and ios. Don’t hesitate to contact me if you had problem about this.