First of all you need to create you application project in Google Api Console,
i will show some steps here how to create the application in Google Api Console,
i will show some steps here how to create the application in Google Api Console,
Registering with Google Cloud Messaging
1. Goto Google APIs Console page and create a new project. (If you haven’t created already otherwise it will take you to dashboard)

2. After creating project you can see the project id in the url. Note down the project id which will be used as SENDER ID in android project. (Example: in #project:460866929976 after semicolon 460866929976 is the sender id)
https://code.google.com/apis/console/#project:460866929976 |

3. After that click on Services on the left panel and turn on Google Cloud Messaging for Android.

4. Once you are done, click on API Access and note down the API Key. This API key will be used when sending requests to GCM server.

now i want to develop one samplepushnotification application
my application structure is like this
GCMIntentService.java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sampleandroidpushnotification; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.RemoteViews; import com.google.android.gcm.GCMBaseIntentService; /** * {@link IntentService} responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { @SuppressWarnings("hiding") private static final String TAG = "GCMIntentService"; public static String EXTRA_MESSAGE ="sendingMessageFromGCMIntent"; public static String TestFlag ="fromGCMIntenet"; public static String globalmessage; static int i=0; static Integer newi; public static String getGlobalmessage() { return globalmessage; } public static void setGlobalmessage(String globalmessage) { GCMIntentService.globalmessage = globalmessage; } public GCMIntentService() { super("xxxxxxxx"); } /** * Issues a notification to inform the user that server has sent a message. */ private static void generateNotification(Context context, String message) { int NOTIFICATION_ID = 1; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.ic_launcher,message, when); Log.v("gcm service",message); String title = context.getString(R.string.app_name); i++; Intent notificationIntent = new Intent(context,TestActivity.class); notificationIntent.putExtra(EXTRA_MESSAGE, message); Log.v("msg","coming"+message); TestFlag = "afterNoti"; // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); notification.setLatestEventInfo(context, title, message, intent); /*notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.defaults |= Notification.DEFAULT_SOUND;*/ notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout); contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher); contentView.setTextViewText(R.id.notification_title, "Sample PushNotification"); contentView.setTextViewText(R.id.text, message); notification.contentView = contentView; // notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification notification.defaults |= Notification.DEFAULT_LIGHTS; // LED notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration notification.defaults |= Notification.DEFAULT_SOUND; // Sound notificationManager.notify(NOTIFICATION_ID, notification); } @Override protected void onError(Context arg0, String arg1) { // TODO Auto-generated method stub } @Override protected void onMessage(Context arg0, Intent arg1) { Log.d("GCM", "RECIEVED A MESSAGE"); // Get the data from intent and send to notificaion bar generateNotification(arg0, arg1.getStringExtra("message")); } @Override protected void onRegistered(Context arg0, String reggId) { // TODO Auto-generated method stub JSONObject json; JSONArray answerArray = new JSONArray(); JSONObject answerObject = new JSONObject(); try { answerObject.put("regId", reggId); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } answerArray.put(answerObject); } @Override protected void onUnregistered(Context arg0, String arg1) { // TODO Auto-generated method stub } }
in the above java file observe
public GCMIntentService() { super("xxxxxxxx"); }
instead of XXXXXXX you just put your sender ID
LKRActivity.java
package com.example.sampleandroidpushnotification; import org.apache.cordova.DroidGap; import android.os.Bundle; import android.view.Menu; public class LKRActivity extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.loadUrl("file:///android_asset/www/index.html"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
MainActivity.java
package com.example.sampleandroidpushnotification; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import com.google.android.gcm.GCMRegistrar; public class MainActivity extends Activity { String regId ; private static final String TAG = "Push Notification Demo Activity"; private static final String SENDER_ID = "XXXXXXXX"; String notificationTitle; String notificationMessage; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); notificationTitle=getIntent().getStringExtra("notificationTitle"); notificationMessage=getIntent().getStringExtra("notificationMessage"); GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { GCMRegistrar.register(this, "XXXXXXXX"); regId = GCMRegistrar.getRegistrationId(this); } else { Log.v(TAG, "Already registered : "+regId); } try { ExecuteRest(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public String ExecuteRest() throws ClientProtocolException, IOException{ Intent notificationIntent = new Intent(this.getApplicationContext(),TestActivity.class); notificationIntent.putExtra("gcmId", regId); notificationIntent.putExtra("notificationMessage", notificationMessage); notificationIntent.putExtra("notificationTitle", notificationTitle); startActivity(notificationIntent); return null; } protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException { InputStream in = entity.getContent(); StringBuffer out = new StringBuffer(); int n = 1; while (n > 0) { byte[] b = new byte[4096]; n = in.read(b); if (n > 0) out.append(new String(b, 0, n)); } return out.toString(); } }
in the above java file observe this two lines
private static final String SENDER_ID = "XXXXXXXX";
GCMRegistrar.register(this, "XXXXXXXX");instead of XXXXXXX you just put your sender IDPush.java
package com.example.sampleandroidpushnotification; import java.util.List; import java.util.Vector; import javapns.communication.exceptions.CommunicationException; import javapns.communication.exceptions.KeystoreException; import javapns.devices.Device; import javapns.devices.Devices; import javapns.devices.exceptions.InvalidDeviceTokenFormatException; import javapns.devices.implementations.basic.BasicDevice; import javapns.feedback.AppleFeedbackServer; import javapns.feedback.AppleFeedbackServerBasicImpl; import javapns.feedback.FeedbackServiceManager; import javapns.notification.AppleNotificationServer; import javapns.notification.AppleNotificationServerBasicImpl; import javapns.notification.NewsstandNotificationPayload; import javapns.notification.Payload; import javapns.notification.PayloadPerDevice; import javapns.notification.PushNotificationManager; import javapns.notification.PushNotificationPayload; import javapns.notification.PushedNotification; import javapns.notification.PushedNotifications; import javapns.notification.transmission.NotificationThread; import javapns.notification.transmission.NotificationThreads; import javapns.notification.transmission.PushQueue; /** * <p>Main class for easily interacting with the Apple Push Notification System</p> * * <p>This is the best starting point for pushing simple or custom notifications, * or for contacting the Feedback Service to cleanup your list of devices.</p> * * <p>The <b>JavaPNS</b> library also includes more advanced options such as * multithreaded transmission, special payloads, and more. * See the library's documentation at <a href="http://code.google.com/p/javapns/">http://code.google.com/p/javapns/</a> * for more information.</p> * * @author Sylvain Pedneault * @see NotificationThreads */ public class Push { private Push() { } /** * Push a simple alert to one or more devices. * * @param message the alert message to push. * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ public static PushedNotifications alert(String message, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { return sendPayload(PushNotificationPayload.alert(message), keystore, password, production, devices); } /** * Push a simple badge number to one or more devices. * * @param badge the badge number to push. * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ public static PushedNotifications badge(int badge, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { return sendPayload(PushNotificationPayload.badge(badge), keystore, password, production, devices); } /** * Push a simple sound name to one or more devices. * * @param sound the sound name (stored in the client app) to push. * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ public static PushedNotifications sound(String sound, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { return sendPayload(PushNotificationPayload.sound(sound), keystore, password, production, devices); } /** * Push a notification combining an alert, a badge and a sound. * * @param message the alert message to push (set to null to skip). * @param badge the badge number to push (set to -1 to skip). * @param sound the sound name to push (set to null to skip). * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ public static PushedNotifications combined(String message, int badge, String sound, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { return sendPayload(PushNotificationPayload.combined(message, badge, sound), keystore, password, production, devices); } /** * Push a content-available notification for Newsstand. * * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ public static PushedNotifications contentAvailable(Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { return sendPayload(NewsstandNotificationPayload.contentAvailable(), keystore, password, production, devices); } /** * Push a special test notification with an alert message containing useful debugging information. * * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ public static PushedNotifications test(Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { return sendPayload(PushNotificationPayload.test(), keystore, password, production, devices); } /** * Push a preformatted payload to a list of devices. * * @param payload a simple or complex payload to push. * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ public static PushedNotifications payload(Payload payload, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { return sendPayload(payload, keystore, password, production, devices); } /** * Push a preformatted payload to a list of devices. * * @param payload a simple or complex payload to push. * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ private static PushedNotifications sendPayload(Payload payload, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { PushedNotifications notifications = new PushedNotifications(); if (payload == null) return notifications; PushNotificationManager pushManager = new PushNotificationManager(); try { AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production); pushManager.initializeConnection(server); List<Device> deviceList = Devices.asDevices(devices); Devices.evaluateEfficiency(deviceList); notifications.setMaxRetained(deviceList.size()); for (Device device : deviceList) { try { BasicDevice.validateTokenFormat(device.getToken()); PushedNotification notification = pushManager.sendNotification(device, payload, false); notifications.add(notification); } catch (InvalidDeviceTokenFormatException e) { notifications.add(new PushedNotification(device, payload, e)); } } } finally { try { pushManager.stopConnection(); } catch (Exception e) { } } return notifications; } /** * Push a preformatted payload to a list of devices using multiple simulatenous threads (and connections). * * @param payload a simple or complex payload to push. * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param numberOfThreads the number of parallel threads to use to push the notifications * @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws Exception thrown if any critical exception occurs */ public static PushedNotifications payload(Payload payload, Object keystore, String password, boolean production, int numberOfThreads, Object devices) throws Exception { if (numberOfThreads <= 0) return sendPayload(payload, keystore, password, production, devices); AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production); List<Device> deviceList = Devices.asDevices(devices); NotificationThreads threads = new NotificationThreads(server, payload, deviceList, numberOfThreads); threads.start(); try { threads.waitForAllThreads(true); } catch (InterruptedException e) { } return threads.getPushedNotifications(true); } /** * Build and start an asynchronous queue for sending notifications later without opening and closing connections. * The returned queue is not started, meaning that underlying threads and connections are not initialized. * The queue will start if you invoke its start() method or one of the add() methods. * Once the queue is started, its underlying thread(s) and connection(s) will remain active until the program ends. * * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param numberOfThreads the number of parallel threads to use to push the notifications * @return a live queue to which you can add notifications to be sent asynchronously * @throws KeystoreException thrown if an error occurs when loading the keystore */ public static PushQueue queue(Object keystore, String password, boolean production, int numberOfThreads) throws KeystoreException { AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production); PushQueue queue = numberOfThreads <= 1 ? new NotificationThread(server) : new NotificationThreads(server, numberOfThreads); return queue; } /** * Push a different preformatted payload for each device. * * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param payloadDevicePairs a list or an array of PayloadPerDevice: {@link java.util.List}<{@link javapns.notification.PayloadPerDevice}>, {@link javapns.notification.PayloadPerDevice PayloadPerDevice[]} or {@link javapns.notification.PayloadPerDevice} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ public static PushedNotifications payloads(Object keystore, String password, boolean production, Object payloadDevicePairs) throws CommunicationException, KeystoreException { return sendPayloads(keystore, password, production, payloadDevicePairs); } /** * Push a different preformatted payload for each device using multiple simulatenous threads (and connections). * * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param numberOfThreads the number of parallel threads to use to push the notifications * @param payloadDevicePairs a list or an array of PayloadPerDevice: {@link java.util.List}<{@link javapns.notification.PayloadPerDevice}>, {@link javapns.notification.PayloadPerDevice PayloadPerDevice[]} or {@link javapns.notification.PayloadPerDevice} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws Exception thrown if any critical exception occurs */ public static PushedNotifications payloads(Object keystore, String password, boolean production, int numberOfThreads, Object payloadDevicePairs) throws Exception { if (numberOfThreads <= 0) return sendPayloads(keystore, password, production, payloadDevicePairs); AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production); List<PayloadPerDevice> payloadPerDevicePairs = Devices.asPayloadsPerDevices(payloadDevicePairs); NotificationThreads threads = new NotificationThreads(server, payloadPerDevicePairs, numberOfThreads); threads.start(); try { threads.waitForAllThreads(true); } catch (InterruptedException e) { } return threads.getPushedNotifications(true); } /** * Push a different preformatted payload for each device. * * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @param payloadDevicePairs a list or an array of PayloadPerDevice: {@link java.util.List}<{@link javapns.notification.PayloadPerDevice}>, {@link javapns.notification.PayloadPerDevice PayloadPerDevice[]} or {@link javapns.notification.PayloadPerDevice} * @return a list of pushed notifications, each with details on transmission results and error (if any) * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ private static PushedNotifications sendPayloads(Object keystore, String password, boolean production, Object payloadDevicePairs) throws CommunicationException, KeystoreException { PushedNotifications notifications = new PushedNotifications(); if (payloadDevicePairs == null) return notifications; PushNotificationManager pushManager = new PushNotificationManager(); try { AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production); pushManager.initializeConnection(server); List<PayloadPerDevice> pairs = Devices.asPayloadsPerDevices(payloadDevicePairs); Devices.evaluateEfficiency(pairs); notifications.setMaxRetained(pairs.size()); for (PayloadPerDevice ppd : pairs) { Device device = ppd.getDevice(); Payload payload = ppd.getPayload(); try { PushedNotification notification = pushManager.sendNotification(device, payload, false); notifications.add(notification); } catch (Exception e) { notifications.add(new PushedNotification(device, payload, e)); } } } finally { try { pushManager.stopConnection(); } catch (Exception e) { } } return notifications; } /** * <p>Retrieve a list of devices that should be removed from future notification lists.</p> * * <p>Devices in this list are ones that you previously tried to push a notification to, * but to which Apple could not actually deliver because the device user has either * opted out of notifications, has uninstalled your application, or some other conditions.</p> * * <p>Important: Apple's Feedback Service always resets its list of inactive devices * after each time you contact it. Calling this method twice will not return the same * list of devices!</p> * * <p>Please be aware that Apple does not specify precisely when a device will be listed * by the Feedback Service. More specifically, it is unlikely that the device will * be listed immediately if you uninstall the application during testing. It might * get listed after some number of notifications couldn't reach it, or some amount of * time has elapsed, or a combination of both.</p> * * <p>Further more, if you are using Apple's sandbox servers, the Feedback Service will * probably not list your device if you uninstalled your app and it was the last one * on your device that was configured to receive notifications from the sandbox. * See the library's wiki for more information.</p> * * @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) * @param password the keystore's password. * @param production true to use Apple's production servers, false to use the sandbox servers. * @return a list of devices that are inactive. * @throws KeystoreException thrown if an error occurs when loading the keystore * @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers */ public static List<Device> feedback(Object keystore, String password, boolean production) throws CommunicationException, KeystoreException { List<Device> devices = new Vector<Device>(); FeedbackServiceManager feedbackManager = new FeedbackServiceManager(); AppleFeedbackServer server = new AppleFeedbackServerBasicImpl(keystore, password, production); devices.addAll(feedbackManager.getDevices(server)); return devices; } }
TestActivity.java
package com.example.sampleandroidpushnotification; import java.io.IOException; import java.util.ArrayList; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.StrictMode; import android.view.Menu; import android.widget.TextView; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Sender; import com.lkr.pushnotifications.NotificationSuccessActivity; @TargetApi(9) public class TestActivity extends Activity { String notificationTitle; String notificationMessage; @TargetApi(9) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); TextView myText = new TextView(this.getApplicationContext()); myText.setText("Success fully registered"); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); Sender sender = new Sender( "XXXXXXXXX"); String regid= getIntent().getExtras().getString("gcmId"); notificationTitle=getIntent().getExtras().getString("notificationTitle"); notificationMessage=getIntent().getExtras().getString("notificationMessage"); Message message = new Message.Builder().addData("message", notificationMessage).build(); ArrayList<String> oneDevice = new ArrayList<String>(); oneDevice.add(regid); // MulticastResult result = sender.send(message, oneDevice, // 1); try { MulticastResult result = sender.send(message, oneDevice, 1); sender.send(message, oneDevice, 1); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Message sent to One Device"); startActivity(new Intent(TestActivity.this, NotificationSuccessActivity.class)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_test, menu); return true; } }
observe the above java file
Sender sender = new Sender( "XXXXXXXXX");
instead of XXXXXXX you just put your API KeyNotificationSuccessActivity.java
package com.lkr.pushnotifications; import org.apache.cordova.DroidGap; import android.os.Bundle; import android.view.Menu; import com.example.sampleandroidpushnotification.R; public class NotificationSuccessActivity extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.loadUrl("file:///android_asset/www/success.html"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
PushNotificationPlugin.java
package com.lkr.pushnotifications; import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import android.content.Intent; import com.example.sampleandroidpushnotification.MainActivity; public class PushNotificationPlugin extends Plugin { public final String ACTION_SEND_NOTIFICATION = "PushNotification"; @Override public PluginResult execute(String action, JSONArray arg1, String callbackId) { PluginResult result = new PluginResult(Status.INVALID_ACTION); if (action.equals(ACTION_SEND_NOTIFICATION)) { try { String notificationTitle = arg1.getString(0); String notificationMessage = arg1.getString(1); sendNotification(notificationTitle, notificationMessage); result = new PluginResult(Status.OK); } catch (JSONException ex) { result = new PluginResult(Status.JSON_EXCEPTION, ex.getMessage()); } } return result; } private String sendNotification(String notificationTitle, String notificationMessage) { //intent = new Intent().setClass(this.cordova.getActivity(), org.apache.cordova.DroidGap.class); Intent intent = new Intent(this.cordova.getActivity(), MainActivity.class); intent.putExtra("notificationTitle", notificationTitle); intent.putExtra("notificationMessage", notificationMessage); this.cordova.getActivity().startActivity(intent); return ""; } }
index.html
<!DOCTYPE html> <html> <title> Push Notification </title> <head> <script src="jquery-1.8.2.js" type= "text/javascript"></script> <script src="jquery.mobile-1.2.0.js" type="text/javascript"></script> <script src="cordova-2.3.0.js" type="text/javascript"></script> <script src="pushnotification.js" type="text/javascript"></script> <script type="text/javascript"> function onDeviceReady () { $('#send').bind('click', function () { //alert('notificationTitle: ' + $('#notificationTitle').val() + ' notificationMessage: ' + $('#notificationMessage').val()); window.plugins.pushnotification.send($('#notificationTitle').val(), $('#notificationMessage').val(), function () { alert('notificationMessage sent successfully'); }, function (e) { alert('notificationMessage Failed:' + e); } ); }); $('#send_by_lkr').bind('click', function () { //alert('notificationTitle: ' + $('#notificationTitle').val() + ' notificationMessage: ' + $('#notificationMessage').val()); window.plugins.pushnotification.send_by_lkr($('#notificationTitle').val(), $('#notificationMessage').val(), function () { alert('notificationMessage sent successfully'); }, function (e) { alert('notificationMessage Failed:' + e); } ); }); } document.addEventListener("deviceready", onDeviceReady, false); </script> <link rel="stylesheet" type="text/css" href= "jquery.mobile-1.2.0.min.css"> <meta name="viewport" content= "width=device-width; height=device-height; user-scalable=no"> </head> <body> <div id="startPage" data-role="page" data-theme="a"> <div data-role="header"> <h1>PushNotification Demo</h1> </div> <div data-role="content"> <!-- <label for="notificationTitle">Notification Title:</label> <input type="tel" id="notificationTitle" name="notificationTitle" placeholder="Notificatio Title"/> --> <label for="notificationMessage">notificationMessage:</label> <textarea id="notificationMessage" name="notificationMessage"></textarea> <a href="#" id="send" data-role="button">Send</a> <!-- <a href="#" id="send_by_lkr" data-role="button">send_by_lkr</a> --> </div> </div> </body> </html>
pushnotification.js
var PushNotificationPlugin = function () {}; PushNotificationPlugin.prototype.send = function (notificationTitle, notificationMessage) { return PhoneGap.exec(null,null , 'PushNotificationPlugin', "PushNotification", [notificationTitle, notificationMessage]); }; PushNotificationPlugin.prototype.send_by_lkr = function(notificationTitle, notificationMessage) { return cordova.exec(this._onEvent, this._onError, "PushNotificationPlugin", "PushNotification", [notificationTitle, notificationMessage]); }; /*PhoneGap.addConstructor(function() { alert("helllo"); PhoneGap.addPlugin("pushnotification", new PushNotificationPlugin()); });*/ cordova.addConstructor(function() { window.pushnotification = new PushNotificationPlugin(); // backwards compatibility window.plugins = window.plugins || {}; window.plugins.pushnotification = window.pushnotification; }); /** * Method called when the child browser has an event. */ PushNotificationPlugin.prototype._onEvent = function(data) { /*if (data.type == PushNotificationPlugin.CLOSE_EVENT && typeof window.plugins.childBrowser.onClose === "function") { window.plugins.childBrowser.onClose(); } if (data.type == ChildBrowser.LOCATION_CHANGED_EVENT && typeof window.plugins.childBrowser.onLocationChange === "function") { window.plugins.childBrowser.onLocationChange(data.location); }*/ alert(data+" success"); }; /** * Method called when the child browser has an error. */ PushNotificationPlugin.prototype._onError = function(data) { /*if (typeof window.plugins.childBrowser.onError === "function") { window.plugins.childBrowser.onError(data); }*/ alert(data+" error"); };
success.html
<!DOCTYPE html> <html> <title> Push Notification </title> <head> <script src="jquery-1.8.2.js" type= "text/javascript"></script> <script src="jquery.mobile-1.2.0.js" type="text/javascript"></script> <script src="cordova-2.3.0.js" type="text/javascript"></script> <script src="pushnotification.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href= "jquery.mobile-1.2.0.min.css"> <meta name="viewport" content= "width=device-width; height=device-height; user-scalable=no"> </head> <body> <div id="startPage" data-role="page" data-theme="a"> <div data-role="header"> <h1>PushNotification Demo</h1> </div> <div data-role="content"> <h1> notificaion success fully sent</h1> <!-- <a href="#" id="send_by_lkr" data-role="button">send_by_lkr</a> --> </div> </div> </body> </html>
config.xml
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <cordova> <!-- access elements control the Android whitelist. Domains are assumed blocked unless set otherwise --> <access origin="http://127.0.0.1*" /> <!-- allow local pages --> <!-- <access origin="https://example.com" /> allow any secure requests to example.com --> <!-- <access origin="https://example.com" subdomains="true" /> such as above, but including subdomains, such as www --> <!-- <access origin=".*"/> Allow all domains, suggested development use only --> <log level="DEBUG" /> <preference name="useBrowserHistory" value="false" /> <plugins> <plugin name="App" value="org.apache.cordova.App"/> <plugin name="Geolocation" value="org.apache.cordova.GeoBroker"/> <plugin name="Device" value="org.apache.cordova.Device"/> <plugin name="Accelerometer" value="org.apache.cordova.AccelListener"/> <plugin name="Compass" value="org.apache.cordova.CompassListener"/> <plugin name="Media" value="org.apache.cordova.AudioHandler"/> <plugin name="Camera" value="org.apache.cordova.CameraLauncher"/> <plugin name="Contacts" value="org.apache.cordova.ContactManager"/> <plugin name="File" value="org.apache.cordova.FileUtils"/> <plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager"/> <plugin name="Notification" value="org.apache.cordova.Notification"/> <plugin name="Storage" value="org.apache.cordova.Storage"/> <plugin name="Temperature" value="org.apache.cordova.TempListener"/> <plugin name="FileTransfer" value="org.apache.cordova.FileTransfer"/> <plugin name="Capture" value="org.apache.cordova.Capture"/> <plugin name="Battery" value="org.apache.cordova.BatteryListener"/> <plugin name="PushNotificationPlugin" value="com.lkr.pushnotifications.PushNotificationPlugin" /> </plugins> </cordova>
manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sampleandroidpushnotification" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <permission android:name="com.example.sampleandroidpushnotification.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.BROADCAST_STICKY" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <uses-permission android:name="com.example.sampleandroidpushnotification.permission.C2D_MESSAGE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.USE_CREDENTIALS" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="com.android.vending.BILLING" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".LKRActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" 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="com.example.sampleandroidpushnotification" /> </intent-filter> </receiver> <service android:name="com.example.sampleandroidpushnotification.GCMIntentService" /> <activity android:name=".TestActivity" android:label="@string/title_activity_test" > </activity> <activity android:name=".MainActivity" android:label="@string/title_activity_main" /> <activity android:name="com.lkr.pushnotifications.NotificationSuccessActivity" android:label="@string/title_activity_main" /> </application> </manifest>
Note:::
you have gcm.jar, gcm-server.jar,JavaPNS_2.3_Beta_2.jar,json-simple-1.1.jar,
the above jar files are there in your libs folder
