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…

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.

IBM Worklight training – Day 2

I just finished my training for day 2. Not too many questions I need to ask today to trainer because yesterday he already gave me the answers regarding to worklight issues. Maybe you can check the issues here. We just done a few of lab sets that he gave to us yesterday. But mostly trainee not understand about this new technology, even worklight already 2 years running in the market.

You can learn more details about the worklight here. But you must aware, worklight only support in eclipse juno r2. Other than that it’s not working. Even you use android studio or eclipse what so ever, still not working. If you had problem with worklight, during the development phase, don’t hesitate to contact me or send direct email to mr Ed Grossman You can reach his email here, edgross@us.ibm.com.

Our lesson for today was application console and JSON store. Application console which we can control the mobile app from the web browser. You can disable the app, set the push notification and set a notification to users. Compare to non worklight mobile app, the push notification we need to set on each platform. Like iOS, we need to set APNs that stands for Apple Push Notification Service. You can check here.

apple push notifcation service

apple push notifcation service

For android, we need to set linked sender id for push notification. It called GCM, stands for Google Cloud Messaging. For both setup, you need 2 accounts, one account for apple developer another one account for google play in other to access these services. JSON Store, according to IBM information centre, it provides the API for storing JSON data locally, it may be linked to an adapter for data synchronization.

google cloud messaging

google cloud messaging

I thinks it enough for today. If I have a opportunity, I will post a tutorial about how to do CRUD operation using Jquery Mobile. Have a nice day !!