The function onNotificationGCM in Cordova PushNotification is not triggered

I am currently working on implementing push notifications for both Android and iOS.

For this task, I have utilized a cordova push-plugin from the following link: https://github.com/phonegap-build/PushPlugin, and so far, it has been functioning excellently.

A quick note: I am working on an AngularJS project.

Within my NotificationHelper factory, I have implemented the following init method:

helper.init = function() {

    // Initialize the push plugin notification
    var pushNotification = window.plugins.pushNotification;

    var errorHandler = function(error) {
        logger.debug('errorHandler = ' + error);
    };

    if ($rootScope.isAndroid()) {
        var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
        pushNotification.register(function(result) {
            logger.debug('successHandler = ' + result);
        }, errorHandler, {
            'senderID' : senderId,
            'ecb' : 'onNotificationGCM'
        });
    }
};

Additionally, I have defined the following methods in mains.js :

var onNotificationGCM = function(event) {
   // Callback to web service in Angular.
   var elem = angular.element(document.querySelector('[ng-app]'));
   var injector = elem.injector();
   var service = injector.get('NotificationHelper');
   service.onNotificationGCM(event);
};

This is a workaround to call an AngularJS factory from main JavaScript.

The 'onNotificationGCM' function calls the 'NotificationHelper.onNotificationGCM' method :

helper.onNotificationGCM = function(e) {
    switch (e.event) {
    case 'message':
        // Notification received while app was in the foreground
        if (e.foreground) {
            logger.debug('[notification] [message] Foreground : ' + JSON.stringify(e));
        } else { // Notification tapped in the notification tray
            logger.debug('[notification] [message] Background : ' + JSON.stringify(e));
            if (e.coldstart) {
                // App was not running and user clicked on notification
            } else {
                // App was running and user clicked on notification
            }
        }
        decriptPayloadNotification(e.payload);
        break;
    case 'registered':
        logger.debug('[notification] [registered] : ' + JSON.stringify(e));
        if (e.regid.length > 0) {
            registerUser(e.regid, 'gcm');
        }
        break;

    case 'error':
        logger.debug('[notification] [error] : ' + JSON.stringify(e));
        break;

    default:
        logger.debug('[notification] [default] : Unknown, an event was received and we do not know what it is : ' + JSON.stringify(e));
        break;
    }
};

Initially, everything works well:

  • 'Registered' event is received
  • Notifications are received
  • When I'm in the foreground, I receive the 'message' event :

NotificationHelper: [notification] [message] Foreground : {"event":"message","from":"847593779913","message":"Agenêts 23/03 10h\r\n","collapse_key":"do_not_collapse","foreground":true,"payload":{"lt":"school","lv":"E1154","notId":"35429","title":"Agenêts le 23/03/2015","message":"Agenêts 23/03 10h\r\n"}}

  • When I'm in the background and receive a notification that I tap in the notification tray, I receive the 'message' event :

NotificationHelper: [notification] [message] Background : {"event":"message","from":"847593779913","message":"la piscine sera fermée 1 journée pour raison technique","coldstart":false,"collapse_key":"do_not_collapse","foreground":false,"payload":{"lt":"swimming pool","lv":"E114","notId":"29869","title":"23/04/2015 fermeture de la piscine","message":"la piscine sera fermée 1 journée pour raison technique"}}

However, if I force quit my app, the functionality stops.

If I restart the app, I no longer receive the 'message' events and the 'onNotificationGCM' method is not called.

I have found some articles discussing this issue, but so far, without any success:

Stackoverflow : Phonegap PushNotification to open a specific app page

Does anyone have any insights or ideas on how to address this problem?

Answer №1

If you are utilizing node-gcm as your push notification server, here are some tips that may help with your query: things to verify:

  • Utilize adb logcat from the console and monitor your device logs to check if your device is receiving any notifications (you should see some logs from gcmservices if it's working). It's important to have these logs, as not seeing them could mean no notifications will be received even when the app is in the foreground.
  • Ensure that you have added "title" and "message" keys to your message data (this tripped me up before)
  • Check that the delayWhileIdle parameter is set to false

Below is a sample of the message variable and method I am using:

var pushAndroidSender = new gcm.Sender('Your GoogleApi Server Key Here');
var message = new gcm.Message({
    collapseKey: 'demo',
    delayWhileIdle: false,
    timeToLive: 3,
    data: {
        "message":"What's up honey?",
        "title":"Come on"
    }
});
pushAndroidSender.send(message, registrationIds, function(err, result) {
    if (err) {
        console.error("An error occurred: " + err);
    } else {
        console.log("Successful result:" + result);
    }
});

Answer №2

After encountering an issue where a plugin was working correctly the first time but not on subsequent launches, I pondered why this might be happening.

  • I had a thought: perhaps the callback function is only subscribed to the plugin the first time and not during subsequent attempts.

It turned out that this was indeed the root cause of my problem. I was only calling "pushNotification.register" once to initialize the plugin and retrieve IDs. However, on future app launches, I neglected to reinstantiate the plugin, resulting in the pushplugin being unaware of which method to invoke in the callback request.

The solution? Make sure to call "pushNotification.register" every time the application is launched!

In my code, it became necessary to invoke the following method on each "deviceready" event:

helper.init = function() {

// Initialize push plugin notification
var pushNotification = window.plugins.pushNotification;

var errorHandler = function(error) {
    logger.debug('errorHandler = ' + error);
};

if ($rootScope.isAndroid()) {
    var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
    pushNotification.register(function(result) {
        logger.debug('successHandler = ' + result);
    }, errorHandler, {
        'senderID' : senderId,
        'ecb' : 'onNotificationGCM'
    });
}
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Filterable Bootstrap table with striped zebra CSS styling

Check out the fiddle I created: http://jsfiddle.net/52aK9/239/ In the fiddle, you may notice that the first two rows are supposed to be grey and the table's zebra or striped design is not displaying correctly as expected. I've attempted various ...

Can bootstrap classes be transformed into pure css code?

Is it possible to translate bootstrap classes into pure CSS? For example, transforming 'class="container-sm' into regular CSS. I am curious about the CSS code associated with the "container-sm" class in bootstrap <div class="container-sm"> ...

Utilizing the child element's attribute value in a list to dynamically modify the CSS styling of a div element

I'm struggling with designing a ranking bar that consists of 9 bars. I want the height of the bars to vary, with bar 0 and bar 8 being the longest. However, I am having difficulty manipulating my jQuery selector to change the CSS style of the bars bas ...

Deploying an Angular application created using Yeoman to Heroku

I have been following some instructions on how to deploy my project, such as this guide or this tutorial. However, I am unable to get it to work properly. This is the code in my server.js file: var app, express, gzippo, morgan; gzippo = require('gz ...

Tips for creating 2 fetch methods for a contact API and a Message API in ReactJS!

I am just starting to learn reactjs and have been able to successfully map data from a JSON API. My goal now is to ensure that when a number is saved in the contact list, it should also display the name in the message list. To achieve this, I plan to creat ...

Using Javascript, verify if a given URL is legitimate and commences with "http://" or "https://"

I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://. Here is the regular expression (RegExp) I have been using: private testIfValidURL(str) { const pattern = new RegExp('^(https?:\\/&bsol ...

Retrieving the special attribute value from a div element

When running the following command: console.log(document.getElementById('container')); The output is as follows: <div id="container" prjid="ABCDE">...</div> But why does the next command: console.log(document.getElementById(&a ...

Click on the following link to view your screen resolution:

As I work on a website that showcases an animation with a resolution of 1024x768, I plan to distribute the link as a Holiday greeting through email. Is there a method to ensure that the website only loads in the specified resolution, even if the user' ...

Tips for aligning an element in the center in relation to its sibling above

Help Needed with Centering Form Button https://i.sstatic.net/QhWqi.png I am struggling to center the "Send" button below the textarea in the form shown in the image. Despite trying various methods like using position absolute, relative, and custom margin ...

Eliminate all key-value pairs from an array of objects except for the specified key-value pair

I've got an array filled with objects const myArr = [ {k1: 1, k2: 1, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4} ] I'm attempting to filter these objects, although I don&apos ...

Is it possible for Vue Router to remember the scroll position on a route and return to the same position when navigating back?

My Vue Router is not saving the scroll position and always loads at the top of the page (0, 0). Any suggestions on what could be causing this issue? Here is my current router code setup: const scrollBehavior = (to, from, savedPosition) => { if (saved ...

JavaScript web developer encounters an issue with MongoDb and Mongoose findOneAndUpdate method, as it unexpectedly returns undefined

I've been attempting to update an item in my mongodb database, but I'm encountering issues as the error keyword is being set to undefined. It's possible that I am making a mistake somewhere. Here's the code for the update function: rou ...

An error occurs when attempting to access data from the JSON file

Currently, I am utilizing an API to retrieve the balance from a bitcoin address. This is my code: async function getWalletBalance(address) { try { const response = await got(`blockchain.info/balance?active=${address}`) return response ...

What is the best method for directing to various pages on a GitHub Pages website?

My GitHub Pages site is live at this link. While the splash page loads perfectly, clicking on the circle to transition to the next page, 'landing.html', leads to a 404 error. I have exhausted all possible solutions to address this issue, includin ...

Passing data from Controller to Factory in AngularJS

Apologies if this is a repeat question, but I have thoroughly searched StackOverflow and couldn't find the answer to my specific issue. Below is the code snippet in question: http://plnkr.co/edit/IsdYMgcIznQ667ols67b?p=preview I am encountering an ...

`Angular RxJS vs Vue Reactivity: Best practices for managing UI updates that rely on timers`

How can you implement a loading spinner following an HTTP request, or any asynchronous operation that occurs over time, using the specified logic? Wait for X seconds (100ms) and display nothing. If the data arrives within X seconds (100ms), display i ...

What is the best way to define the appearance of Ionic features?

The Ionic framework adapts the appearance of its features based on whether the app is running on Android or iOS, but it also offers a unique third look exclusive to Ionic. My query pertains to whether there is a method to specify the specific visual style ...

Accessing the current route in a Vuex module using Vue.js

I've created a vuex store with namespaces that retrieves a specific store entry based on the current route parameter. import Router from '../../router/index' const options = { routeIdentifier: 'stepId' } export function fetchFr ...

Is it possible to bypass the standard syntax and manipulate geometry buffers directly in three.js in order to achieve improved performance?

Embarking on a creative journey into the realm of geometry generation and manipulation, I am eager to explore intricate and large-scale projects. While I am familiar with the conventional methods of achieving this, as demonstrated in the informative respon ...

Using Node.js to update information within Firebase

Here's a problem I'm facing: I have a cron job running in Node.js that sends data to a Firebase database every minute. The issue is, even when there are no changes, the database still receives information. Take a look at my code snippet below: l ...