images (1)

Android Push notification

images (1)

Android Push notification

Download Code from below link

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

Manual Installation

1) Install GCM support files

  • copy the contents of src/android/com/ to your project’s src/com/ folder.

  • copy the contents of libs/ to your libs/ folder.

  • copy {android_sdk_path}/extras/android/support/v13/android-support-v13.jar to your libs/ folder.

The final hierarchy will likely look something like this:

{project_folder}
    libs
        gcm.jar
        android-support-v13.jar
        cordova-3.4.0.jar
    src
        com
            plugin
                gcm
                    CordovaGCMBroadcastReceiver.java
                    GCMIntentService.java
                    PushHandlerActivity.java
                    PushPlugin.java
            {company_name}
                {intent_name}
                    {intent_name}.java

2) Modify your AndroidManifest.xml and add the following lines to your manifest tag:

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <permission android:name="$PACKAGE_NAME.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="$PACKAGE_NAME.permission.C2D_MESSAGE" /> 

3) Modify your AndroidManifest.xml and add the following activityreceiver and service tags to your applicationsection. (See the Sample_AndroidManifest.xml file in the Example folder.)

<activity android:name="com.plugin.gcm.PushHandlerActivity"/>
<receiver android:name="com.plugin.gcm.CordovaGCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
 <intent-filter>
 <action android:name="com.google.android.c2dm.intent.RECEIVE" />
 <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
 <category android:name="$PACKAGE_NAME" />
 </intent-filter>
</receiver>
<service android:name="com.plugin.gcm.GCMIntentService" />

4) Check that the launch mode for the main Cordova Activity is one of the singleXXX options inAndroidManifest.xml.

<activity ... android:launchMode="singleTop">

Otherwise a new activity instance, with a new webview, will be created when activating the notifications.

5) Modify your res/xml/config.xml to include the following line in order to tell Cordova to include this plugin and where it can be found: (See the Sample_config.xml file in the Example folder)

<feature name="PushPlugin">
 <param name="android-package" value="com.plugin.gcm.PushPlugin" />
</feature>

6) Add the PushNotification.js script to your assets/www folder (or javascripts folder, wherever you want really) and reference it in your main index.html file. This file’s usage is described in the Plugin API section below.

<script type="text/javascript" charset="utf-8" src="PushNotification.js"></script>

Plugin API

n the plugin examples folder you will find a sample implementation showing how to interact with the PushPlugin. Modify it to suit your needs.

pushNotification

The plugin instance variable.

var pushNotification;

document.addEventListener("deviceready", function(){
 pushNotification = window.plugins.pushNotification;
 ...
});

register

To be called as soon as the device becomes ready.

$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
if ( device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos" ){

 pushNotification.register(
 successHandler,
 errorHandler,
 {
 "senderID":"replace_with_sender_id",
 "ecb":"onNotification"
 });
} else {
 pushNotification.register(
 tokenHandler,
 errorHandler,
 {
 "badge":"true",
 "sound":"true",
 "alert":"true",
 "ecb":"onNotificationAPN"
 });
}

On success, you will get a call to tokenHandler (iOS), onNotification (Android and Amazon Fire OS), or onNotificationWP8 (WP8), allowing you to obtain the device token or registration ID, or push channel name and Uri respectively. Those values will typically get posted to your intermediary push server so it knows who it can send notifications to.

Note: Android: If you have not already done so, you’ll need to set up a Google API project, to generate your senderID. Follow these steps to do so. This is described more fully in the Testing section below. In this example, be sure and substitute your own senderID. Get your senderID by signing into to your google dashboard. The senderID is found at Overview->Dashboard->Project Number.

successHandler

Called when a plugin method returns without error

// result contains any message sent from the plugin call
function successHandler (result) {
 alert('result = ' + result);
}

errorHandler

Called when the plugin returns an error

// result contains any error description text returned from the plugin call
function errorHandler (error) {
 alert('error = ' + error);
}

Event callback

Event callback that gets called when your device receives a notification

function onNotification(e) {
 $("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');

 switch( e.event )
 {
 case 'registered':
 if ( e.regid.length > 0 )
 {
 $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
 // 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 )
 {
 $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');

 // on Android soundname is outside the payload.
 // On Amazon FireOS all custom attributes are contained within payload
 var soundfile = e.soundname || e.payload.sound;
 // if the notification contains a soundname, play it.
 var my_media = new Media("/android_asset/www/"+ soundfile);
 my_media.play();
 }
 else
 { // otherwise we were launched because the user touched a notification in the notification tray.
 if ( e.coldstart )
 {
 $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
 }
 else
 {
 $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
 }
 }

 $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
 //Only works for GCM
 $("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
 //Only works on Amazon Fire OS
 $status.append('<li>MESSAGE -> TIME: ' + e.payload.timeStamp + '</li>');
 break;

 case 'error':
 $("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
 break;

 default:
 $("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
 break;
 }
}

Looking at the above message handling code for Android/Amazon Fire OS, a few things bear explanation. Your app may receive a notification while it is active (INLINE). If you background the app by hitting the Home button on your device, you may later receive a status bar notification. Selecting that notification from the status will bring your app to the front and allow you to process the notification (BACKGROUND). Finally, should you completely exit the app by hitting the back button from the home page, you may still receive a notification. Touching that notification in the notification tray will relaunch your app and allow you to process the notification (COLDSTART). In this case the coldstart flag will be set on the incoming event. You can look at the foregroundflag on the event to determine whether you are processing a background or an in-line notification. You may choose, for example to play a sound or show a dialog only for inline or coldstart notifications since the user has already been alerted via the status bar.

For Amazon Fire OS, offline message can also be received when app is launched via carousel or by tapping on app icon from apps. In either case once app delivers the offline message to JS, notification will be cleared.

Since the Android and Amazon Fire OS notification data models are much more flexible than that of iOS, there may be additional elements beyond message. You can access those elements and any additional ones via thepayload element. This means that if your data model should change in the future, there will be no need to change and recompile the plugin.

senderID (Android only)

This is the Google project ID you need to obtain by registering your application for GCM


unregister

You will typically call this when your app is exiting, to cleanup any used resources. Its not strictly necessary to call it, and indeed it may be desireable to NOT call it if you are debugging your intermediarry push server. When you call unregister(), the current token for a particular device will get invalidated, and the next call to register() will return a new token. If you do NOT call unregister(), the last token will remain in effect until it is invalidated for some reason at the GCM/ADM side. Since such invalidations are beyond your control, its recommended that, in a production environment, that you have a matching unregister() call, for every call to register(), and that your server updates the devices’ records each time.

pushNotification.unregister(successHandler, errorHandler, options);

Server:

GCM.PHP

<?php

class DB_Functions {

 private $db;

 //put your code here

 // constructor

 function __construct() {

 include_once './db_connect.php';

 // connecting to database

 $this->db = new DB_Connect();

 $this->db->connect();

 }

 // destructor

 function __destruct() {

 }

 /**

 * Storing new user

 * returns user details

 */

 public function storeUser($name, $email, $gcm_regid) {

 // insert user into database

 $result = mysql_query("INSERT INTO gcm_users(name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())");

 // check for successful store

 if ($result) {

 // get user details

 $id = mysql_insert_id(); // last inserted id

 $result = mysql_query("SELECT * FROM gcm_users WHERE id = $id") or die(mysql_error());

 // return user details

 if (mysql_num_rows($result) > 0) {

 return mysql_fetch_array($result);

 } else {

 return false;

 }

 } else {

 return false;

 }

 }

 /**

 * Get user by email and password

 */

 public function getUserByEmail($email) {

 $result = mysql_query("SELECT * FROM gcm_users WHERE email = '$email' LIMIT 1");

 return $result;

 }

 /**

 * Getting all users

 */

 public function getAllUsers() {

 $result = mysql_query("select * FROM gcm_users");

 return $result;

 }

 /**

 * Check user is existed or not

 */

 public function isUserExisted($email) {

 $result = mysql_query("SELECT email from gcm_users WHERE email = '$email'");

 $no_of_rows = mysql_num_rows($result);

 if ($no_of_rows > 0) {

 // user existed

 return true;

 } else {

 // user not existed

 return false;

 }

 }

}

?>

register.php

<?php

// response json

$json = array();

/**

 * Registering a user device

 * Store reg id in users table

 */

if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"])) {

 $name = $_POST["name"];

 $email = $_POST["email"];

 $gcm_regid = $_POST["regId"]; // GCM Registration ID

 // Store user details in db

 include_once './db_functions.php';

 include_once './GCM.php';

 $db = new DB_Functions();

 $gcm = new GCM();

 $res = $db->storeUser($name, $email, $gcm_regid);

 $registatoin_ids = array($gcm_regid);

 $message = array("product" => "shirt");

 $result = $gcm->send_notification($registatoin_ids, $message);

 echo $result;

} else {

 // user details missing

}

?>

 

send_messege.php

<?php

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

if (isset($_GET["regId"]) && isset($_GET["message"])) {

 $regId = $_GET["regId"];

 $message = $_GET["message"];

 include_once './GCM.php';

 $gcm = new GCM();

 $registatoin_ids = array($regId);

 $message = array("price" => $message);

 $result = $gcm->send_notification($registatoin_ids, $message);

 echo $result;

}

?>

 

config.php

<?php

/**

 * Database config variables

 */

define("DB_HOST", "localhost");

define("DB_USER", "");

define("DB_PASSWORD", "");

define("DB_DATABASE", "");

/*

 * Google API Key

 */

define("GOOGLE_API_KEY", ""); // Place your Google API Key

?>

 

db_connect.php

<?php

class DB_Connect {

 // constructor

 function __construct() {

 }

 // destructor

 function __destruct() {

 // $this->close();

 }

 // Connecting to database

 public function connect() {

 require_once 'config.php';

 // connecting to mysql

 $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

 // selecting database

 mysql_select_db(DB_DATABASE);

 // return database handler

 return $con;

 }

 // Closing database connection

 public function close() {

 mysql_close();

 }

} 

?>

</pre>
<pre>

db_function.php

<?php

class DB_Functions {

 private $db;

 //put your code here

 // constructor

 function __construct() {

 include_once './db_connect.php';

 // connecting to database

 $this->db = new DB_Connect();

 $this->db->connect();

 }

 // destructor

 function __destruct() {

 }

 /**

 * Storing new user

 * returns user details

 */

 public function storeUser($name, $email, $gcm_regid) {

 // insert user into database

 $result = mysql_query("INSERT INTO gcm_users(name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())");

 // check for successful store

 if ($result) {

 // get user details

 $id = mysql_insert_id(); // last inserted id

 $result = mysql_query("SELECT * FROM gcm_users WHERE id = $id") or die(mysql_error());

 // return user details

 if (mysql_num_rows($result) > 0) {

 return mysql_fetch_array($result);

 } else {

 return false;

 }

 } else {

 return false;

 }

 }

 /**

 * Get user by email and password

 */

 public function getUserByEmail($email) {

 $result = mysql_query("SELECT * FROM gcm_users WHERE email = '$email' LIMIT 1");

 return $result;

 }

 /**

 * Getting all users

 */

 public function getAllUsers() {

 $result = mysql_query("select * FROM gcm_users");

 return $result;

 }

 /**

 * Check user is existed or not

 */

 public function isUserExisted($email) {

 $result = mysql_query("SELECT email from gcm_users WHERE email = '$email'");

 $no_of_rows = mysql_num_rows($result);

 if ($no_of_rows > 0) {

 // user existed

 return true;

 } else {

 // user not existed

 return false;

 }

 }

}

?>

</pre>
<pre>

Test.php

<!--

To change this template, choose Tools | Templates

and open the template in the editor.

-->

<!DOCTYPE html>

<html>

 <head>

 <title></title>

 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

 <script type="text/javascript">

 $(document).ready(function(){

 });

 </script>

 </head>

 <body>

 <form name="" method="post" action="register.php">

 <input type="text" name="name"/>

 <input type="text" name="email"/>

 <input type="text" name="regId"/>

 <input type="submit"/>

 </form>

 </body>

</html>

</pre>
<pre>

Data Base Script:

</pre>
<span style="color: #333333;"><span style="font-size: medium;">CREATE TABLE IF NOT EXISTS `gcm_users` (</span></span>

<span style="color: #333333;"><span style="font-size: medium;">`id` int(11) NOT NULL AUTO_INCREMENT,</span></span>

<span style="color: #333333;"><span style="font-size: medium;">`gcm_regid` text,</span></span>

<span style="color: #333333;"><span style="font-size: medium;">`name` varchar(50) NOT NULL,</span></span>

<span style="color: #333333;"><span style="font-size: medium;">`email` varchar(255) NOT NULL,</span></span>

<span style="color: #333333;"><span style="font-size: medium;">`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,</span></span>

<span style="color: #333333;"><span style="font-size: medium;">PRIMARY KEY (`id`)</span></span>

<span style="color: #333333;"><span style="font-size: medium;">) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;</span></span>
<pre>

Aniruddha Mukherjee

Aniruddha Mukherjee

Android and iOs consultant.

More Posts

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Add a Comment

HTML Snippets Powered By : XYZScripts.com