Having trouble enabling push notifications on Android with ngCordova

Having trouble with push notifications through the ngCordova plugin. Followed the sample code from

(with a slight change - no deviceready listener, code inside ionicPlatform.ready listener)

Below is the code snippet:

angular.module('myApp', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $rootScope, $state, $cordovaPush) {
  $ionicPlatform.ready(function() {
    var config = {
      "senderID": "myID100001000"
    };

    $cordovaPush.register(config).then(function(result) {
      alert(result);
    }, function(err) {
      alert(err);
    })      
  }); 

  $rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
    switch(notification.event) {
      case 'registered':
        if (notification.regid.length > 0 ) {
          alert('registration ID = ' + notification.regid);
        }
        break;

      default:
        alert('An unknown GCM event has occurred');
        break;
    }
  });  
})

Upon app start, the "OK" alert shows up confirming successful $cordovaPush.register call. Expected a "registered" notification event right after but never received it.

Seeking assistance. Much appreciated!

Answer №1

While the solution is hinted at in the comments, a proper answer is needed.

It's crucial to note that the register callback will always return OK if you provide a valid senderID. However, if the

$cordovaPush:notificationReceived
event isn't triggered (which may take a moment), it indicates that the ID could be incorrect.

Remember to utilize the Project Number instead of the Project ID.

To acquire the number, navigate to the API Console, choose your project, and you'll land on the Overview page. At the top of this page, you'll find something similar to this:

Project ID: your-project-id        Project Number: 0123456789

Simply copy and employ the project number, and everything should function properly.

Answer №2

Dealing with this issue extensively, I've come to discover that there are currently two iterations of the cordova push plugin available:

While both versions are compatible with ngCordova, only the outdated one is properly documented.

The deprecated version goes by $cordovaPush while the newer one is labeled as $cordovaPushV5, each boasting distinct functionalities.

In my case, the issue arose when attempting to integrate the cordova-plugin-push using outdated documentation from the ngCordova platform.

The provided code snippet illustrates how to implement the latest version for Push notifications successfully:

 /*
         * Current iteration of Push notification events
         */
        function registerV5() {

            $ionicLoading.show({
                template: '<ion-spinner></ion-spinner>'
            });

            if (ionic.Platform.is('browser')) {
                alert("You are running on browser, please switch to your device for notifications.");
                $ionicLoading.hide();
                return;
            }

            /**
             * Configuration doc:
             * https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#pushnotificationinitoptions
             */
            var GCM_PROJECT_ID = 'xxxxxx';

            $cordovaPushV5.initialize({
                "android": {
                    "clearNotifications": false,
                    "senderID" : GCM_PROJECT_ID
                }
            });

            $cordovaPushV5.register().then(function (deviceToken) {
                console.log("Successfully registered", deviceToken);

                $scope.data.deviceToken = deviceToken;

                // Below code required to configure $cordovaPushV5 notifications emitter. 
                // Don't pass function it's not handler.
                $cordovaPushV5.onNotification();
                $cordovaPushV5.onError();

                $ionicLoading.hide();
            }, function (error) {
                console.log("Failed registration");
                console.log("error object : ", error);
                $ionicLoading.hide();
            });
        }

        $rootScope.$on('$cordovaPushV5:notificationReceived', function(event, data) {
            console.log("notification received");
            console.log("data object: ", data);

            var foreground = data.additionalData.foreground || false;
            var threadID = data.additionalData.payload.threadID || '';
            var group = data.additionalData.payload.group || false;

            if (foreground) {
                // Handle foreground push notifications
                console.log('Receive notification in foreground');
            } else {
                // Manage push messages while app is in background or closed
                console.log('Receive notification in background');
                // Open FB Messenger app when user clicks notification UI while app is inactive.
                if (typeof data.additionalData.coldstart != "undefined" && data.additionalData.coldstart == false)
                    if (!group)
                        // Open FB Messenger chat window for specific user
                        window.open('fb-messenger://user/' + threadID, '_system', 'location=no');
                    else
                        // Open FB Messenger group chat window
                        window.open('fb-messenger://groupthreadfbid/' + threadID, '_system', 'location=no');                
            }
        });

        $rootScope.$on('$cordovaPushV5:errorOccurred', function(event, error) {
            console.log("notification error occurred");
            console.log("event object: ", event);
            console.log("error object: ", error);
        });

Further insights can be found on Github at: https://github.com/driftyco/ng-cordova/issues/1125 and on this resource: https://github.com/yafraorg/yafra/wiki/Blog-Ionic-PushV5

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

Is it possible to include spaces in a JavaScript alert message?

Is it possible to add spaces in an alert message? I have been trying to include spaces in my alert messages, but the alerts do not appear when there are spaces. Example where it works: https://jsfiddle.net/yczrhztg/ Example where it doesn't work: ht ...

Is there a way to include a React component within the setContent method of Leaflet?

Is there a way to trigger a React JS component in setContent? I am looking for a solution to add a button within a popup Leaflet, which when clicked will call a React component. While I am aware of the "reactDomserver.rendertostring" method to co ...

NodeJS Express Application Error: Unable to access /url

I've been troubleshooting this issue for an hour now and I'm stumped. I can't seem to access the specified URL. I created a NodeJs Express app, but when I try to access http://localhost:3000/users/login, I receive the error message Cannot GE ...

Picture in the form of a radio button

Is there a way to use an image instead of a radio button in my AngularJS form? I have managed to hide the radio button using CSS, but it disables the checked event. How can I make the image clickable? position: absolute; left: -9999px; Here is the code s ...

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...

Struggling to add custom styles to an Ionic radio button

I'm struggling to adjust the position of the icon in an Ionic radio button so that it sits a bit higher, but I can't seem to figure out how to do it. Below is the code snippet for reference: // HTML <ion-radio class="radio-input" mo ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

The width of Material UI Grid decreases every time it is re-rendered

I'm attempting to display a list of 25 words in a 5x5 grid using the MUI Grid component. The grid is structured as a <Grid container direction="column"> with five <Grid item> elements. Each <Grid item> contains: <Grid co ...

Using the filter() function in jQuery allows for efficient sorting and

My current area of study is in jQuery, but I'm encountering a bit of confusion with the following code: var list = mylist.filter(function(f) { return $(f) .find('.anthing') .length > 0; }); I'm particularly puzz ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

Converting Venn diagram code from JavaScript <script> tags to Angular 2: A step-by-step guide

I am struggling to incorporate a Venn diagram into my Angular 2+ project. I followed the code sample provided at - http://jsfiddle.net/johnpham92/h04sknus/ To begin, I executed the following command - npm install venn.js Then I proceeded with impl ...

Ways to verify if a Discord.js snowflake is present in a collection of other identification numbers

I'm currently developing a Discord.js bot and I want to create a system where only specific IDs listed in a JSON file can trigger certain commands. However, I'm unsure about how to implement this logic within an if statement. if (message.author. ...

Retrieve a file from a URL using Javascript's AJAX functionality

I have a CSV file uploaded to the server that I need to parse using JavaScript/jQuery. When trying to fetch the file with an AJAX call, I keep getting an error: XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is prese ...

explore a nested named view using ui-router

My app has a view called mainContent. <div class = "wrapper" ui-view = "mainContent"> </div> There is only one route for this view. $stateProvider .state("home", { url: "/home", vi ...

Exception: Closing the database connection failed: db.close is not a callable

I have this Node.js application that utilizes MongoDb: const MongoClient = require('mongodb').MongoClient; const demoPerson = { name:'Jane', lastName:'Doe' }; const findKey = { name: 'Jane' }; MongoClient.connect( ...

Combining two forms into one PHP page, but intending to submit only a single form

I'm facing an issue on my page where I have both a sign-in and a sign-up form. Whenever I click on either the sign-in or sign-up button, it always ends up submitting the sign-up form. What am I doing wrong? Here's the PHP code snippet: if($_SE ...

Perform activities within a component responsible for displaying a flatlist

I have a component called Post that I'm using to display posts within a FlatList. Currently, the Post component only shows text and images in the Flatlist. However, within the Post component, there are buttons that should have functionality such as de ...

Navigating the issue of updateMany not functioning properly in mongoose and nodejs

I need assistance with updating the author name of a post whenever the user updates their profile name. My code is as follows: router('/:id', async (req, res) { if (req.body._id == req.params.id) { try { const user = await ...

Can the data retrieved from a jsonp call that may be considered "bad" be utilized effectively?

When making a JSONP call to another domain, I am receiving data that is in JSON format but not wrapped in a function. This causes a parse error to occur. However, the data is still retrievable and visible. Despite the error, is it possible to utilize the ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...