Giter Site home page Giter Site logo

phonegap-build / pushplugin Goto Github PK

View Code? Open in Web Editor NEW

This project forked from bobeast/pushplugin-deprecated

1.3K 93.0 999.0 10.97 MB

This repository is deprecated head to phonegap/phonegap-push-plugin

Home Page: https://github.com/phonegap/phonegap-plugin-push

License: MIT License

JavaScript 57.56% Ruby 0.36% CSS 3.16% Java 20.78% Objective-C 8.91% C# 4.62% HTML 4.61%

pushplugin's Introduction

[DEPRECATED] Cordova Push Notifications Plugin for Android, iOS, WP8, Windows8, BlackBerry 10 and Amazon Fire OS

This plugin is deprecated, i.e. it is no longer maintained. Going forward additional features and bug fixes will be added to the new phonegap-plugin-push repository.

DESCRIPTION

This plugin is for use with Cordova, and allows your application to receive push notifications on Amazon Fire OS, Android, iOS, Windows Phone and Windows8 devices.

Important - Push notifications are intended for real devices. They are not tested for WP8 Emulator. The registration process will fail on the iOS simulator. Notifications can be made to work on the Android Emulator, however doing so requires installation of some helper libraries, as outlined here, under the section titled "Installing helper libraries and setting up the Emulator".

Contents

## LICENSE

The MIT License

Copyright (c) 2012 Adobe Systems, inc.
portions Copyright (c) 2012 Olivier Louvignes

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

##Manual Installation

Manual Installation for Amazon Fire OS

  1. Install the ADM library
  • Download the Amazon Mobile App SDK and unzip.
  • Create a folder called ext_libs in your project's platforms/amazon-fireos folder.
  • Copy amazon-device-messaging-x.x.x.jar into the ext_libs folder above.
  • Create a new text file called ant.properties in the platforms/amazon-fireos folder, and add a java.compiler.classpath entry pointing at the library. For example: java.compiler.classpath=./ext_libs/amazon-device-messaging-1.0.1.jar
  1. Copy the contents of the Push Notification Plugin's src/amazon/com folder to your project's platforms/amazon-fireos/src/com folder.

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

<permission android:name="$PACKAGE_NAME.permission.RECEIVE_ADM_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="$PACKAGE_NAME.permission.RECEIVE_ADM_MESSAGE" />
<uses-permission android:name="com.amazon.device.messaging.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
  1. Modify your AndroidManifest.xml and add the following activity, receiver and service tags to your application section.
<amazon:enable-feature android:name="com.amazon.device.messaging" android:required="true"/>
<service android:exported="false" android:name="com.amazon.cordova.plugin.ADMMessageHandler" />
<activity android:name="com.amazon.cordova.plugin.ADMHandlerActivity" />
<receiver android:name="com.amazon.cordova.plugin.ADMMessageHandler$Receiver" android:permission="com.amazon.device.messaging.permission.SEND">
	<intent-filter>
        	<action android:name="com.amazon.device.messaging.intent.REGISTRATION" />
                <action android:name="com.amazon.device.messaging.intent.RECEIVE" />
                <category android:name="$PACKAGE_NAME" />
	</intent-filter>
</receiver>
  1. If you are using Cordova 3.4.0 or earlier, modify your AndroidManifest.xml and add "amazon" XML namespace to tag:
xmlns:amazon="http://schemas.amazon.com/apk/res/android"
  1. Modify res/xml/config.xml to add a reference to PushPlugin:
<feature name="PushPlugin" >
	<param name="android-package" value="com.amazon.cordova.plugin.PushPlugin"/>
</feature>
  1. Modify res/xml/config.xml to set config options to let Cordova know whether to display ADM message in the notification center or not. If not, provide the default message. By default, message will be visible in the notification. These config options are used if message arrives and app is not in the foreground (either killed or running in the background).
<preference name="showmessageinnotification" value="true" />
<preference name="defaultnotificationmessage" value="New message has arrived!" />
  1. Create an file called api_key.txt in the platforms/amazon-fireos/assets folder containing the API Key from the "Security Profile Android/Kindle Settings" tab on the Amazon Developer Portal. For detailed steps on how to register for ADM please refer to section below: Registering your app for Amazon Device Messaging (ADM)

Manual Installation for Android

  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
  1. 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" />
  1. Modify your AndroidManifest.xml and add the following activity, receiver and service tags to your application section. (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" />
  1. Check that the launch mode for the main Cordova Activity is one of the singleXXX options in AndroidManifest.xml.
<activity ... android:launchMode="singleTop">

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

  1. 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>
  1. 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>

Manual Installation for iOS

Copy the following files to your project's Plugins folder:

AppDelegate+notification.h
AppDelegate+notification.m
PushPlugin.h
PushPlugin.m

Add a reference for this plugin to the plugins section in config.xml:

<feature name="PushPlugin">
  <param name="ios-package" value="PushPlugin" />
</feature>

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.

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

Manual Installation for WP8

Copy the following files to your project's Commands folder and add it to the VS project:

PushPlugin.cs

Add a reference to this plugin in config.xml:

<feature name="PushPlugin">
  <param name="wp-package" value="PushPlugin" />
</feature>

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.

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

Do not forget to reference the cordova.js as well.

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

In your Visual Studio project add reference to the Newtonsoft.Json.dll as well - it is needed for serialization and deserialization of the objects.

Also you need to enable the "ID_CAP_PUSH_NOTIFICATION" capability in Properties->WMAppManifest.xml of your project.

Manual Installation for Windows8

Add the src/windows8/PushPluginProxy.js script to your www folder and reference it in your main index.html file.

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

Do not forget to reference the cordova.js as well.

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

To receive toast notifications additional toastCapable=’true’ attribute is required to be manually added in manifest file.

##Automatic Installation

Below are the methods for installing this plugin automatically using command line tools. For additional info, take a look at the Plugman Documentation and Cordova Plugin Specification.

Note: For each service supported - ADM, APNS, GCM or MPNS - you may need to download the SDK and other support files. See the Manual Installation instructions below for more details about each platform.

Cordova

The plugin can be installed via the Cordova command line interface:

  1. Navigate to the root folder for your phonegap project. 2) Run the command.
cordova plugin add https://github.com/phonegap-build/PushPlugin.git

Phonegap

The plugin can be installed using the Phonegap command line interface:

  1. Navigate to the root folder for your phonegap project. 2) Run the command.
phonegap local plugin add https://github.com/phonegap-build/PushPlugin.git

Plugman

The plugin is based on plugman and can be installed using the Plugman command line interface:

plugman install --platform [PLATFORM] --project [TARGET-PATH] --plugin [PLUGIN-PATH]

where
	[PLATFORM] = ios, amazon-fireos, android, wp8, windows8 or blackberry10
	[TARGET-PATH] = path to folder containing your phonegap project
	[PLUGIN-PATH] = path to folder containing this plugin

## Plugin API

In 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 if ( device.platform == 'blackberry10'){
    pushNotification.register(
    successHandler,
    errorHandler,
    {
        invokeTargetId : "replace_with_invoke_target_id",
        appId: "replace_with_app_id",
        ppgUrl:"replace_with_ppg_url", //remove for BES pushes
        ecb: "pushNotificationHandler",
        simChangeCallback: replace_with_simChange_callback,
        pushTransportReadyCallback: replace_with_pushTransportReady_callback,
        launchApplicationOnPush: true
    });
} 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), onNotificationWP8 (WP8) or successHandler (Blackberry10), 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

  • Amazon Fire OS: "ecb" MUST be provided in order to get callback notifications. If you have not already registered with Amazon developer portal,you will have to obtain credentials and api_key for your app. This is described more in detail in the Registering your app for Amazon Device Messaging (ADM) section below.

  • 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.

  • BlackBerry10: "ecb" MUST be provided to get notified of incoming push notifications. Also note, if doing a public consumer (BIS) push, you need to manually add the _sys_use_consumer_push permission to config.xml. <rim:permit system="true">_sys_use_consumer_push</rim:permit>. In order to receieve notifications, an invoke target must be setup for push. See BlackBerry Push Service for additional information about blackberry push options.

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);
}

ecb (Amazon Fire OS, Android and iOS)

Event callback that gets called when your device receives a notification

// iOS
function onNotificationAPN (event) {
	if ( event.alert )
	{
		navigator.notification.alert(event.alert);
	}

	if ( event.sound )
	{
		var snd = new Media(event.sound);
		snd.play();
	}

	if ( event.badge )
	{
		pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
	}
}
// Android and Amazon Fire OS
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;
  }
}
// BlackBerry10
function pushNotificationHandler(pushpayload) {
    var contentType = pushpayload.headers["Content-Type"],
        id = pushpayload.id,
        data = pushpayload.data;//blob

    // If an acknowledgement of the push is required (that is, the push was sent as a confirmed push
    // - which is equivalent terminology to the push being sent with application level reliability),
    // then you must either accept the push or reject the push
    if (pushpayload.isAcknowledgeRequired) {
        // In our sample, we always accept the push, but situations might arise where an application
        // might want to reject the push (for example, after looking at the headers that came with the push
        // or the data of the push, we might decide that the push received did not match what we expected
        // and so we might want to reject it)
        pushpayload.acknowledge(true);
    }
};

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 foreground flag 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 the payload 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

tokenHandler (iOS only)

Called when the device has registered with a unique device token.

function tokenHandler (result) {
    // 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.
    alert('device token = ' + result);
}

setApplicationIconBadgeNumber (iOS only)

Set the badge count visible when the app is not running

pushNotification.setApplicationIconBadgeNumber(successCallback, errorCallback, badgeCount);

The badgeCount is an integer indicating what number should show up in the badge. Passing 0 will clear the badge.

unregister (Amazon Fire OS, Android and iOS)

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);

WP8

register (WP8 Only)

if(device.platform == "Win32NT"){
    pushNotification.register(
        channelHandler,
        errorHandler,
        {
            "channelName": "channelName",
            "ecb": onNotificationWP8,
            "uccb": channelHandler,
            "errcb": jsonErrorHandler
        });
}

Make sure that date and time settings are correct for your device/emulator before registering for push notifications.

channelHandler (WP8 only)

Called after a push notification channel is opened and push notification URI is returned. The application is now set to receive notifications.

ecb (WP8 Only)

Event callback that gets called when your device receives a notification. This is fired if the app is running when you receive the toast notification, or raw notification.

//handle MPNS notifications for WP8
function onNotificationWP8(e) {

	if (e.type == "toast" && e.jsonContent) {
		pushNotification.showToastNotification(successHandler, errorHandler,
		{
			"Title": e.jsonContent["wp:Text1"], "Subtitle": e.jsonContent["wp:Text2"], "NavigationUri": e.jsonContent["wp:Param"]
		});
		}

	if (e.type == "raw" && e.jsonContent) {
		alert(e.jsonContent.Body);
	}
}

uccb (WP8 only)

Event callback that gets called when the channel you have opened gets its Uri updated. This function is needed in case the MPNS updates the opened channel Uri. This function will take care of showing updated Uri.

errcb (WP8 only)

Event callback that gets called when server error occurs when receiving notification from the MPNS server (for example invalid format of the notification).

function jsonErrorHandler(error) {
		$("#app-status-ul").append('<li style="color:red;">error:' + error.code + '</li>');
		$("#app-status-ul").append('<li style="color:red;">error:' + error.message + '</li>');
	}

showToastNotification (WP8 only)

Show toast notification if app is deactivated.

pushNotification.showToastNotification(successCallback, errorCallback, options);

The toast notification's properties are set explicitly using json. They can be get in onNotificationWP8 and used for whatever purposes needed.

To control the launch page when the user taps on your toast notification when the app is not running, add the following code to your mainpage.xaml.cs

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    try
    {
        if (this.NavigationContext.QueryString["NavigatedFrom"] == "toast") // this is set on the server
        {
            this.PGView.StartPageUri = new Uri("//www/index.html#notification-page", UriKind.Relative);
        }
    }
    catch (KeyNotFoundException)
    {
    }
}

Or you can add another Page2.xaml just for testing toast navigate url. Like the MSDN Toast Sample

To test the tile notification, you will need to add tile images like the MSDN Tile Sample

unregister (WP8 Only)

When using the plugin for wp8 you will need to unregister the push channel you have register in case you would want to open another one. You need to know the name of the channel you have opened in order to close it. Please keep in mind that one application can have only one opened channel at time and in order to open another you will have to close any already opened channel.

function unregister() {
	var channelName = $("#channel-btn").val();
	pushNotification.unregister(
		successHandler, errorHandler,
			{
				"channelName": channelName
			});
}

You'll probably want to trap on the backbutton event and only call this when the home page is showing. Remember, the back button on android is not the same as the Home button. When you hit the back button from the home page, your activity gets dismissed. Here is an example of how to trap the backbutton event;

function onDeviceReady() {
	$("#app-status-ul").append('<li>deviceready event received</li>');

	document.addEventListener("backbutton", function(e)
	{
		$("#app-status-ul").append('<li>backbutton event received</li>');

		if( $("#home").length > 0 )
		{
			e.preventDefault();
			pushNotification.unregister(successHandler, errorHandler);
			navigator.app.exitApp();
		}
		else
		{
			navigator.app.backHistory();
		}
	}, false);

	// additional onDeviceReady work...
}

For the above to work, make sure the content for your home page is wrapped in an element with an id of home, like this;

<div id="home">
	<div id="app-status-div">
		<ul id="app-status-ul">
			<li>Cordova PushNotification Plugin Demo</li>
		</ul>
	</div>
</div>

windows

Sample usage is showed below. Note. To be able to receive toast notifications additional toastCapable=’true’ attribute is required in manifest file. Cordova-windows 4.0.0 release adds this property to config.xml. You can use: <preference name="WindowsToastCapable" value="true" /> in config.xml. However, you will need Cordova 5.1.1 which pins Cordova-windows 4.0.0.

// fired when push notification is received
window.onNotification = function (e) {
    navigator.notification.alert('Notification received: ' + JSON.stringify(e));
}  
var pushNotification = window.plugins.pushNotification;
pushNotification.register(successHandler, errorHandler, {"channelName":"your_channel_name","ecb":"onNotification"});

function successHandler(result) {
    console.log('registered###' + result.uri);
    // send uri to your notification server
}
function errorHandler(error) {
    console.log('error###' + error);
}

See Sending push notifications with WNS to send test push notification.

## Testing The notification system consists of several interdependent components.

  1. The client application which runs on a device and receives notifications.
  2. The notification service provider (ADM for Amazon Fire OS, APNS for Apple, GCM for Google, MPNS for WP8)
  3. Intermediary servers that collect device IDs from clients and push notifications through ADM, APNS GCM or MPNS.

This plugin and its target Cordova application comprise the client application.The ADM, APNS, GCM and MPNS infrastructure are maintained by Amazon, Apple, Google and Microsoft, respectively. In order to send push notifications to your users, you would typically run an intermediary server or employ a 3rd party push service. This is true for all ADM (Amazon), APNS (iOS), GCM (Android) and MPNS (WP8) notifications. However, when testing the notification client applications, it may be desirable to be able to push notifications directly from your desktop, without having to design and build those server's first. There are a number of solutions out there to allow you to push from a desktop machine, sans server.

Testing APNS and GCM notifications

An easy solution to test APNS and GCM is a ruby gem called pushmeup (tested only on Mac, but it probably works fine on Windows as well).

Prerequisites:

  • Ruby gems is installed and working.
  • You have successfully built a client with this plugin, on both iOS and Android and have installed them on a device.
  • You have installed the PushMeUp gem: $ sudo gem install pushmeup

APNS/iOS Setup

Follow this tutorial to create a file called ck.pem.

Start at the section entitled "Generating the Certificate Signing Request (CSR)", and substitute your own Bundle Identifier, and Description.

  1. Go the this plugin's Example/server folder and open pushAPNS.rb in the text editor of your choice.
  2. Set the APNS.pem variable to the path of the ck.pem file you just created
  3. Set APNS.pass to the password associated with the certificate you just created. (warning this is cleartext, so don't share this file)
  4. Set device_token to the token for the device you want to send a push to. (you can run the Cordova app / plugin in Xcode and extract the token from the log messages)
  5. Save your changes.

Android/GCM Setup

Follow these steps to generate a project ID and a server based API key.

  1. Go the this plugin's Example/server folder and open pushGCM.rb in the text editor of your choice.
  2. Set the GCM.key variable to the API key you just generated.
  3. Set the destination variable to the Registration ID of the device. (you can run the Cordova app / plugin in on a device via Eclipse and extract the regID from the log messages)

Sending a test notification

  1. cd to the directory containing the two .rb files we just edited.
  2. Run the Cordova app / plugin on both the Android and iOS devices you used to obtain the regID / device token, respectively.
  3. $ ruby pushGCM.rb or $ ruby pushAPNS.rb

If you run this demo using the emulator you will not receive notifications from GCM. You need to run it on an actual device to receive messages or install the proper libraries on your emulator (You can follow this guide under the section titled "Installing helper libraries and setting up the Emulator") If everything seems right and you are not receiving a registration id response back from Google, try uninstalling and reinstalling your app. That has worked for some devs out there.

While the data model for iOS is somewhat fixed, it should be noted that GCM is far more flexible. The Android implementation in this plugin, for example, assumes the incoming message will contain a 'message' and a 'msgcnt' node. This is reflected in both the plugin (see GCMIntentService.java) as well as in provided example ruby script (pushGCM.rb). Should you employ a commercial service, their data model may differ. As mentioned earlier, this is where you will want to take a look at the payload element of the message event. In addition to the cannonical message and msgcnt elements, any additional elements in the incoming JSON object will be accessible here, obviating the need to edit and recompile the plugin. Many thanks to Tobias Hößl for this functionality!

Testing ADM Notifications for Amazon Fire OS

####Register your app for Amazon Device Messaging (ADM)

  1. Create a developer account on Amazon Developer Portal
  2. Add a new app and turn Device Messaging switch to ON. Create a sample app for your device so you have the app name and package name used to register online.
  3. Create Security Profile and obtain ADM credentials for your app.

Sending a test notification

  1. Inside the plugin's examples/server folder, open the pushADM.js NodeJS script with a text editor. (You should already have NodeJS installed).
  2. Edit the CLIENT_ID and CLIENT_SECRET variables with the values from the ADM Security Profile page for your app. This will allow your app to securely identify itself to Amazon services.
  3. Compile and run the sample app on your device. Note the sample app requires the Cordova Device and Media plugins to work.
  4. The sample app will display your device's registration ID. Copy that value (it's very long) from your device into pushADM.js, entered in the REGISTRATION_IDS array. To test sending messages to more than one device, you can enter in multiple REGISTRATION_IDS into the array.
  5. To send a test push notification, run the test script via a command line using NodeJS: $ node pushADM.js.

Testing MPNS Notification for WP8

The simplest way to test the plugin is to create an ASP.NET webpage that sends different notifications by using the URI that is returned when the push channel is created on the device.

You can see how to create one from MSDN Samples:

Sending push notifications on BlackBerry10

If doing a BES push, ensure the device has been enterprise activated, has network access (wifi or sim) and your app is installed in the work permiter. You also need to make sure the _sys_use_consumer_push permission is NOT specified in the config.xml. This permission is meant only for public consumer BIS pushes and will cause an error when registering.

If doing a public consumer BIS push, please ensure the _sys_use_consumer_push permission is added to the config.xml.

Both types of pushes require the use of a Push Initiator.

For additional information on BlackBerry Push see https://developer.blackberry.com/services/push/.

Troubleshooting and next steps

If all went well, you should see a notification show up on each device. If not, make sure you are not being blocked by a firewall, and that you have internet access. Check and recheck the token id, the registration ID and the certificate generating process.

In a production environment, your app, upon registration, would send the device id (iOS) or the registration id (Android/Amazon), to your intermediary push server. For iOS, the push certificate would also be stored there, and would be used to authenticate push requests to the APNS server. When a push request is processed, this information is then used to target specific apps running on individual devices.

If you're not up to building and maintaining your own intermediary push server, there are a number of commercial push services out there which support both APNS and GCM.

##Additional Resources

## Acknowledgments

Huge thanks to Mark Nutter whose GCM-Cordova plugin forms the basis for the Android side implimentation.

Likewise, the iOS side was inspired by Olivier Louvignes' Cordova PushNotification Plugin (Copyright (c) 2012 Olivier Louvignes) for iOS.

Props to Tobias Hößl, who provided the code to surface the full JSON object up to the JS layer.

pushplugin's People

Contributors

actemedia avatar archananaik avatar armno avatar bbosman avatar bmatto avatar bobeast avatar chriswiggins avatar colene avatar cuatl avatar eddyverbruggen avatar edewit avatar fesor avatar filmaj avatar goya avatar jdhiro avatar keab42 avatar kenwu27 avatar macdonst avatar madebycm avatar markeeftb avatar mkuklis avatar nadyaa avatar purplecabbage avatar rjmunro avatar russellbeattie avatar sclement41 avatar sebastiansier avatar sgrebnov avatar smorstabilini avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pushplugin's Issues

PushPlugin in iOs 7

Hi,

I'm using phonegap 2.9 and xCode 5.

After I updated xCode 5 and build my app on iOs7 iPhone 5 there was a build error:
8:31: Property 'uniqueIdentifier' not found on object of type 'UIDevice *'

at line: [results setValue:dev.uniqueIdentifier forKey:@"deviceUuid"];

I already tried to replace uniqueIdentifier with identifierForVendor and uniqueAppInstanceIdentifier, but no succes.

Can anyone help me with this?
Thanks in advance!

Build Error after adding this plugin

When I try to build the app, I get the below error and build fails.

I am using cordova 2.9

[javac] /Volumes/space/HCM/Sencha/Project/HCMDoctor/src/com/plugin/gcm/GCMIntentService.java:20: error: package android.support.v4.app does not exist
[javac] import android.support.v4.app.NotificationCompat;
[javac] ^
[javac] /Volumes/space/HCM/Sencha/Project/HCMDoctor/src/com/plugin/gcm/GCMIntentService.java:94: error: package NotificationCompat does not exist
[javac] NotificationCompat.Builder mBuilder =
[javac] ^
[javac] /Volumes/space/HCM/Sencha/Project/HCMDoctor/src/com/plugin/gcm/GCMIntentService.java:95: error: package NotificationCompat does not exist
[javac] new NotificationCompat.Builder(context)
[javac] ^
[javac] 3 errors

If I do NOT register the app every time it loads then the push notification flow is broken

Hi,

I don't understand why I have to call "pushNotification.register(...)" every time the app initializes. IMHO after a successful registration I can save (persist) the regid and re-use it every time the app loads. This eliminating the need to register over and over again.

Unfortunately, if I try to do this then the push notification flow is broken :-(
This happens because the PushPlugin.java class initializes "gECB" and "gWebView" fields only when "pushNotification.register(...)" is called.
Because I save the regid and do not call the register method, then these class fields remain null which causes methods like "sendExtras(Bundle extras)" and "sendJavascript(JSONObject _json)" not to work!

Any insights on this matter will be appreciated :-)
Thanks in advance,
Amit

manual copy of *.m / *.h files ?

I had to do this:

cp plugins/PushPlugin-1.3.3/src/ios/* platforms/ios/CordovaTest/Plugins/

was expecting the "cordova plugin add...." would do that for me

isEnabled

You have the code to check if push notifications are disabled on the ios device but give no way to access this information.

How can i use this great plugin with PHP?

Hello i install this plugin on an iPod device i prove, a static push notification and it works! reading tutorial, i saw a oration like "Those values will typically get posted to your intermediary push server so it knows who it can send notifications to." this refers that i need a server? if this the case... how can i put the url ro my server from the aplication plugin? is there any fix for this? my problem is, i want to send notification when my client up a new slider from his page... something easy... but how i send a push notifiction when this action started? obviusly i need to write my server url like "www.mysite.com/apnservice.php?method=requestpush" or something like that with javascript, can anybody helpme?? thanks!

successHandler does not fire when calling register on Android

I'm more or less using the boilerplate example code, which includes this line for registering a device on Android:

pushNotification.register(successHandler, errorHandler, {"senderID":"[my sdk id]","ecb":"onNotificationGCM"}); 

However, when launching this app, the successHandler callback function is never fired. On iOS, the equivalent function, tokenHandler does fire.

We also receive a registration notification back from the server, which fires in this:

      case 'registered':
        if (e.regid.length > 0) {
          window.alert('<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;

We can work around this since the notification is coming back, but something seems to be wrong with the register callback on Android.

Define APNS data in cold-start functionality?

Where do I have to define the APNS data in cold-start functionality?

The register function can't be executed because I'm probably missing some settings:

$("#app-status-ul").append('

  • registering iOS
  • ');
    pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});

    Where do I need to define the APNS settings? config.xml?

    Thanks in advance

    Can't receive my reg ID and didn't show me any Error

    Hi,

    I installed PushPlugin in fresh project but I get this messages :

    09-30 15:50:36.119: V/PushPlugin(982): execute: action=register
    09-30 15:50:36.130: V/PushPlugin(982): execute: data=[{"senderID":"85546438302","ecb":"onNotificationGCM"}]
    09-30 15:50:36.160: V/PushPlugin(982): execute: jo={"senderID":"85546438302","ecb":"onNotificationGCM"}
    09-30 15:50:36.160: V/PushPlugin(982): execute: ECB=onNotificationGCM senderID=85546438302
    09-30 15:50:36.192: D/GCMRegistrar(982): resetting backoff for com.push
    09-30 15:50:36.300: V/GCMRegistrar(982): Registering app com.push of senders 85546438302
    09-30 15:50:37.339: D/DroidGap(982): onMessage(spinner,stop)

    Thx for help.

    using with phonegap build - not working

    Hi,
    I am trying to use the plugin via phonegap build.
    I have added the <script> reference to the html, and the PushNotification.js itself, and when the "register" function is called, nothing happens..
    I would expect the successHandler or errorHandler to be fired, and show an alert, but nothing happens, and the try-catch doesn't catch nothing..

    please help..

    No event after coldstart on android

    I cannot achieve to read the message data when launching the app after a coldstart.

    Has somewhen went to perform this?
    Is there something to avoid at the start of the app?

    Testing my jquery mobile app on Android with Phonegap Build:

    App ID
    182602

    Version
    2.0.0

    PhoneGap
    2.9.0

    Error: grafting xml at selector "plugins" - Phonegap 3.0

    The plugman install method for 3.0 fails to insert xml into the AndroidManifest.xml and Config.xml files. Cordova also fails to insert the xml if I use the new CLI install method to add the plugin to the /plugins folder and allow phonegap to auto-load it on build. I couldn't get it to work after tinkering with the plugin.xml file, so maybe something else is going on with the new version?

    I also can't get it to work using the manual instructions instead of the automatic build, but I don't think you can do that any more with the new version, anyway.

    iOS ecb callback not firing with PushNotification plugin

    I've done a full write up of the problem on the PG Build forum, as I assumed to begin with that this was an issue with Build.

    They have directed me to post an issue here, though, so here you go :)

    http://community.phonegap.com/nitobi/topics/ios_ecb_callback_not_firing_with_pushnotification_plugin

    The summary of the post is:
    Using more or less the boilerplate example, everything works as expected on Android. iOS calls the token handler, but does not call the ecb callback. If the app is in the background the notice is displayed in the notification area or the lock screen on iOS, but activating the app still doesn't cause the ecb handler to run.

    iOS Notifications not shown in lock screen

    Environment: iOS 6 using phoengap build with hydration turned on.

    In app and closed app notifications are working fine but if the app goes into the background (by locking the phone) no notifications are shown.

    Is there a way I can capture the background notifications and bubble them up to the user?

    Phonegap v3.x

    Is it possible to use the plugin with phongap v3.x (yet)?

    I could'nt get it running, the readme.md seems not to be very helpful here.

    Should I use plugman? or does the plugin need upgrading for use via the new node based cli tools? ("cordova plugin add ...")

    Tested only on Android yet (phonegap 3.0 on a mac, followed manual install, using cordova-3.0.0.jar)

    "adb logcat" output:

    W/PluginManager(31200): THREAD WARNING: exec() call to PushPlugin.register 
    blocked the main thread for 30ms. Plugin should use 
    CordovaInterface.getThreadPool().
    

    Cheers,
    Michael

    files in wrong folders?

    i had to move 'PushPlugin.java' and 'PushHandlerActivity.java' from GCM to gcm to get this to work. Capitalization matter in file names on most systems.

    Dismiss iOS Notification When Tapped

    At least as of version 1.2.2, tapping a notification on iOS opens the app correctly, but the notification is not dismissed. It's not easy for me to test higher versions of the PushPlugin because I use Icenium (which is still working on custom plugins), but I don't see any changes in the code related to this issue. Has this been fixed, or is this possible to be corrected? Thanks.

    Hook-up "error" event to ecb callback

    If there is a registration failure on Android, onError/onRecoverableError methods are invoked. These method need to be implemented to send JS callback to ECB with "event" being "error".

    registration error , invalid sender ?

    06-20 16:54:03.126: V/GCMBaseIntentService(1313): Intent service name: GCMIntentService-GCMIntentService-3
    06-20 16:54:03.136: V/GCMRegistrar(1313): Registering receiver
    06-20 16:54:03.136: D/GCMBaseIntentService(1313): handleRegistration: registrationId = null, error = INVALID_SENDER, unregistered = null
    06-20 16:54:03.136: D/GCMBaseIntentService(1313): Registration error: INVALID_SENDER
    06-20 16:54:03.136: E/GCMIntentService(1313): onError - errorId: INVALID_SENDER
    06-20 16:54:03.136: V/GCMBaseIntentService(1313): Releasing wakelock

    this error come when i using this plugin , now i am testing with emulator installed necessary sdks,

    showing registrationId = null , i also create a projectid on google api in GCM.

    if anyone can help me then solv my problem?

    PushPlugin on iOs not using PhoneGap Build with Phonegap 3.0

    Hello People,

    I can´t get the plugin working.

    • placed the .h and .m files in the Plugins folder
    • .js in the www folder and a reference in index.html
    • plugin reference in config.xml outside the www folder

    feature name="PushPlugin" <- not sure if this is correct
    param name="ios-package" value="PushPlugin"
    feature

    I'm missing 1 thing, inside my www folder I have another plugin folder. The facebook connect plugin had a folder to add, named "org.apache.cordova.core.facebook.Connect". Should there be a folder named "org.apache.cordova.PushPlugin"?

    In my onDeviceReady I placed the code
    var pushNotification;
    pushNotification = window.plugins.pushNotification;
    pushNotification.register(tokenHandler, errorHandler {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});

    After this the application just shows white screen with no errors.

    I hope anyone can help me out.
    Thanks in advance.

    Unregister Issue

    Hi guys,
    i'm using your plugin and it works like a charm. There is just one issue. If i unregistered a device and i send notification to that unregistered id it can receive message anyway. there is just my issue or there is no unregistration on gcm?

    there is no way unregister old registered id? my issue is that i receive a message for every id for every push notification i send.

    Thank you for you help.
    Regards

    ERROR: Plugin 'PushPlugin' not found, or is not a CDVPlugin

    When testing on android works perfect, but when testing on an iPhone device or Simulator the plugin does not work and I get this error log:

    2013-09-12 10:46:31.972 MyApp[7261:907] Multi-tasking -> Device: YES, App: YES
    2013-09-12 10:46:32.163 MyApp[7261:907] active
    2013-09-12 10:46:32.547 MyApp[7261:907] Resetting plugins due to page load.
    2013-09-12 10:46:32.842 MyApp[7261:907] DEPRECATION NOTICE: The Connection ReachableViaWWAN return value of '2g' is deprecated as of Cordova version 2.6.0 and will be changed to 'cellular' in a future release.
    2013-09-12 10:46:32.912 MyApp[7261:907] console, device.platform: iOS
    2013-09-12 10:46:32.913 MyApp[7261:907] ERROR: Plugin 'PushPlugin' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
    2013-09-12 10:46:32.914 MyApp[7261:907] -[CDVCommandQueue executePending] [Line 116] FAILED pluginJSON = [
    "PushPlugin692037132",
    "PushPlugin",
    "register",
    [
    {
    "alert" : "true",
    "ecb" : "onNotificationAPN",
    "sound" : "true",
    "badge" : "true"
    }
    ]
    ]
    2013-09-12 10:46:32.927 MyApp[7261:907] Finished load of: file:///var/mobile/Applications/12D7B223-779E-44F1-9785-FFE103B995E0/MyApp.app/www/index.html

    I have followed all the steps for the manual install, and all ios plugin files are in the plugin folder and referenced to the project.

    I just noticed there is an xcode confix.xml file and I am not sure if I need to add the plugin line to this file as the tutorial is not clear about this.

    I have generated my ios plarform code with cordova 2.9.0.

    Thanks in advance if anyone can help me on what I am doing wrong.

    Urban Airship Copyright Notice

    Hi,

    I am using this plugin and noticed that the copyright notice in the PushPlugin.h and PushPlugin.m files contain a copyright notice from Urban Airship with the following stipulation:

     2. Redistributions in binaryform must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided withthe distribution.
    

    Are these terms that I need to include within the copyright notice of my application? I did not see any mentions of it in the documentation.

    "no valid 'aps-environment' entitlement string found for application" on iOS with Phonegap Build

    I've use Phonegap build with PushPlugin to do Push notification for Android and iOS

    In Android version everything work perfectly ,but in iOS version i've got error

    "no valid 'aps-environment' entitlement string found for application"

    I do some research for this error , they said I MUST use DISTRIBUTED provisioning profile , and I'm sure I do everything correctly in signing process.

    Please let me know how to fix this problem or some link that make sure I can solve problem, I have no progress for 2 days .

    Sorry for my bad English and thank in advance .

    Domiiez

    some problem in xCode 4.6.3

    in PushPlugin.m:

    - (void)dealloc
    {
    //    [notificationMessage release];
        self.notificationCallbackId = nil;
        self.callback = nil;
    
    //    [super dealloc];
    }
    

    in AppDelegate+notification.m:

    - (void)dealloc
    {
        self.launchNotification = nil; // clear the association and release the object
    //    [super dealloc];
    }
    

    how can i fix this without this 3 comments?

    Eclips compiler error after copy plugin/gcm folder

    I have a working Eclipse project, where I'd like to build in push notificatoins.
    After I copy the folders from src/android/com/ to my src/com/, Eclipse is giving me the next error:

    [2013-07-24 07:51:28 - Dex Loader] Unable to execute dex: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;
    [2013-07-24 07:51:28 - MyApp] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;
    

    Is this a known error, and even better, does anyone know how to solve this?

    Why would I want to unregister?

    The documentation is a bit unclear on why I should unregister? Is'nt the whole point of push notifications that the server should be able to notify the user at any time? If I unregister on app exit then the user would only receive notifications while he's using the app?

    Can't get the registration id Android

    I'd like to have the registration id when I'm using register but I just got this:

    09-14 12:35:36.115: V/PushPlugin(14078): execute: action=register
    09-14 12:35:36.115: V/PushPlugin(14078): execute: data=[{"senderID":"My Sender Id","ecb":"onNotificationGCM"}]
    09-14 12:35:36.115: V/PushPlugin(14078): execute: jo={"senderID":"My Sender Id","ecb":"onNotificationGCM"}
    09-14 12:35:36.115: V/PushPlugin(14078): execute: ECB=onNotificationGCM senderID=My Sender Id
    

    I had a look to the java code and I think that I need a gCachedExtras not null to get my sender id, but gCachedExtras is always null.

    And the onRegistered in the GCMIntentService is not used too

    Thanks for your help

    Why calling unregister() on application exit

    Hi,

    As far as I can understand from the description of the unregister() function, you recommend that we call it on application exit. Or as you say, we should have a matching unregister() call for each register().

    This does not make much sense to me. When I call register(), it is to obtain a push token, send it to my web service and then use it to push notifications to the device. This is the common pattern with push notifications, valid for all providers - APN, GCM, MPNS.

    If I call unregister() when the user exists the app, the push token gets invalidated, meaning no notifications unless the app is running. Am I missing something here? Can you please explain this?

    Thanks.

    Not getting notifications in device

    Hello

    I have successfully done things. in my app i m getting the token as well.
    When i m running php script with same token number and ck.pem with it i m getting connected to APNS Message successfully delivered . But no notification in the app even after copying four files in plugins folder and implementing code for notification as onNotificationAPN function. I have included js file in index.html and updated config.xml as well.Please help.

    Thanx in advance.

    Don't ask for GET_TASKS permission

    This PR is bad:
    #3

    The problem is that https://github.com/phonegap-build/PushPlugin/blob/master/src/android/com/plugin/gcm/GCMIntentService.java#L150 is using getRunningTasks() to determine if the app is in the foreground. This is explicitly discouraged as being unreliable, as well as requiring a permission that only some sort of task manager or very intrusive spyware would actually really need:
    http://stackoverflow.com/questions/3667022/android-is-application-running-in-background/5862048#5862048

    Adding getApplicationIconBadgeNumber

    I'm wondering if anyone has thought about adding a getApplicationIconBadgeNumber method to PushNotification.js? I think this would be a good addition to PushPlugin. It would give the ability to check if there were any notifications missed while the app was suspended or closed.

    Reference Error for errorCallback in function setApplicationIconBadgeNumber

    Using Phonegap Build 2.5.0 (having debug issues with 2.7.0 and IOS).

    When pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
    is called a reference error for errorCallback occurs. Looking at PushNotification.js not sure if errorCallback should have been a passed in parameter.

    Unable to try any fix as Phonegap Build auto includes PushNotification.js

    Implementing offline push notifications

    For when wanting to get the information of the push notification in your app, for example to display a message

    I'm not implementing pull request because I know that the way I hacked the notificationRecived probably can be made better. I have zero knowledge on C#

    in appDelegate.m --> - (BOOL)application:(UIApplication_)application didFinishLaunchingWithOptions:(NSDictionary_)launchOptions

        if (launchOptions != nil)
        {
            NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
            NSLog(@"Launched from push notification: %@" , dictionary);
            if (dictionary != nil)
            {
                // get the necessary information out of the dictionary
                // (the data you sent with your push message)
                // and load your data
                PushPlugin *pushHandler = [self.viewController getCommandInstance:@"PushPlugin"];
                pushHandler.notificationMessage = dictionary;
                pushHandler.isInline = YES;
                [pushHandler notificationReceived];
    
            }
        }

    This will call the plugin.

    PushPlugin.m --> - (void)notificationReceived

    - (void)notificationReceived {
    
        if (notificationMessage) {
    
            NSString *exists = [self.webView stringByEvaluatingJavaScriptFromString:@"isLoaded()"];
            NSString *MyTrue = @"true";
    
            if ([MyTrue isEqualToString:exists]) {
                NSLog(@"Notification received isNotLoading");
    
                NSMutableString *jsonStr = [NSMutableString stringWithString:@"{"];
    
                [self parseDictionary:notificationMessage intoJSON:jsonStr];
    
                if (isInline) {
                    [jsonStr appendFormat:@"foreground:'%d',", 1];
                    isInline = NO;
                }
    
                [jsonStr appendString:@"}"];
    
                NSLog(@"Msg: %@", jsonStr);
    
                NSString * jsCallBack = [NSString stringWithFormat:@"%@(%@);", self.callback, jsonStr];
    
                [self.webView stringByEvaluatingJavaScriptFromString:jsCallBack];
    
                self.notificationMessage = nil;
    
            } else {
                NSLog(@"Notification received isLoading");
                [NSTimer scheduledTimerWithTimeInterval: 5 target: self selector: @selector(notificationReceived) userInfo: nil repeats: NO];
            }        
        }
    }

    I try to see if the webview is available, if not I loop, if someone has a better idea please do tell!

    In my javascript

    var loaded = "false";
    
    function isLoaded () {
        return loaded;
    }
    
    $(document).ready(function () {
        loaded = "true";
    });

    I use $(document).ready because I use jquery and I want to check that jquery is working!

    Hope this helps someone!

    unregister and the docs

    The docs say "You will typically call this when your app is exiting, to cleanup any used resources" and "...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."

    However iOS says "You should call this method in rare circumstances only, such as when a new version of the application drops support for remote notifications." This seems contradictory to the PushPlugin docs.

    Also, if you do invalidate the token on app exit, how would you send a notification to the device when the app was not running?

    Trigger a js function when a GenericPush notification is send

    Hi,

    I'm using push notifications with Phonegap Build for iOS.

    I can receive notifications: it's showing an alert and adds an entry to the notification center. Nice ;-)

    But once I click that notification, I want to do something with it in the app.
    How can this be done? Now the app just launches, but I can't find a way to catch it there (e.g. to show it in tha app and store it locally)

    I have the "ecb" callback function triggered when the app is already open when the notification is send, but this function is not triggered when I launch the app by clicking a notification.

    Any options for this?

    On Android, all works fine.

    tnx!

    Dont build using cordova build to Iphone or Android

    I install the plugin using "cordova plugin add https://github.com/phonegap-build/PushPlugin", i need to add to config.xml to android and ios project (issue of cordova-cli), later of install i make a "cordova build but throw this error":

    IOS:

    /Users/jrqb182/Repositories/tmp2/platforms/ios/HelloCordova/Plugins/com.adobe.plugins.PushPlugin/AppDelegate+notification.m:116:6: error: ARC forbids explicit message send of 'dealloc'

    ANDROID:

    -compile:
    [javac] Compiling 8 source files to /Users/jrqb182/Repositories/tmp2/platforms/android/bin/classes
    [javac] /Users/jrqb182/Repositories/tmp2/platforms/android/src/com/plugin/gcm/PushPlugin.java:14: package org.apache.cordova.api does not exist
    [javac] import org.apache.cordova.api.CallbackContext;
    [javac] ^
    [javac] /Users/jrqb182/Repositories/tmp2/platforms/android/src/com/plugin/gcm/PushPlugin.java:15: package org.apache.cordova.api does not exist
    [javac] import org.apache.cordova.api.CordovaPlugin;
    [javac] ^
    [javac] /Users/jrqb182/Repositories/tmp2/platforms/android/src/com/plugin/gcm/PushPlugin.java:23: cannot find symbol
    [javac] symbol: class CordovaPlugin
    [javac] public class PushPlugin extends CordovaPlugin {
    [javac] ^
    [javac] /Users/jrqb182/Repositories/tmp2/platforms/android/src/com/plugin/gcm/PushPlugin.java:44: cannot find symbol
    [javac] symbol : class CallbackContext
    [javac] location: class com.plugin.gcm.PushPlugin
    [javac] public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    [javac] ^
    [javac] /Users/jrqb182/Repositories/tmp2/platforms/android/src/com/plugin/gcm/PushPlugin.java:40: cannot find symbol
    [javac] symbol : variable cordova
    [javac] location: class com.plugin.gcm.PushPlugin
    [javac] return this.cordova.getActivity().getApplicationContext();
    [javac] ^
    [javac] /Users/jrqb182/Repositories/tmp2/platforms/android/src/com/plugin/gcm/PushPlugin.java:57: cannot find symbol
    [javac] symbol : variable webView
    [javac] location: class com.plugin.gcm.PushPlugin
    [javac] gWebView = this.webView;
    [javac] ^
    [javac] /Users/jrqb182/Repositories/tmp2/platforms/android/src/com/plugin/gcm/PushPlugin.java:43: method does not override or implement a method from a supertype
    [javac] @OverRide
    [javac] ^
    [javac] /Users/jrqb182/Repositories/tmp2/platforms/android/src/com/plugin/gcm/PushPlugin.java:214: cannot find symbol
    [javac] symbol : variable super
    [javac] location: class com.plugin.gcm.PushPlugin
    [javac] super.onDestroy();
    [javac] ^
    [javac] 8 errors

    Galaxy android 4.1.2 only gets one notification

    When resetting cache and all the app gets yet another one - works perfect on ios.

    But otherwise unreliable on android: Seems the app works after a remove and reinstall - then it gets notifications. (except for android 4.1.2 only gets one)

    I'm near a deadline, and about ready to jump into the android code - any guidance?

    Handle Application Start due to Remote Notification Case on iOS

    On iOS, this plugin handles the case when application is inactive or in active state and a remote notification is received. However, when application is not running and a remote notification arrives and user clicks the alert/banner, the application launches but PushPlugin does nothing - it should propagate the notification from native(objective C) to Javascript/HTML.

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google ❤️ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.