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

Transfer the elements from one array list to another array list

I need to duplicate the array list below $scope.medicinelist = [ {medicine: 'AMLOPRES 5MG TABLET'}, {medicine: 'ARGIPREG SACHET'}, {medicine: 'ALCIPRO 500MG TABLET'} , {medicine: 'PROLOMET AM 50MG TABLET'}, {medic ...

The output generated by grunt-contrib-handlebars differs from that of the handlebars npm task

Looking for some help with a problem similar to the one mentioned in this Stack Overflow question. Since that question hasn't been answered yet, I decided to create my own post. I'm currently attempting to precompile my handlebars template files ...

Utilizing javascript to reverse an array and seamlessly filling in the missing elements

Consider an array containing data with increasing percentage values and some missing entries. For instance: { "months": 11, "factor": 1.31, "upperMonths": 10.5, "lowerMonths": 11.49, "limit": 20, "percentage": 8 }, { "mont ...

Using React.render to render an empty subcomponent within a jsdom environment

Experimenting with React in node using jsdom has been an interesting challenge for me. I encountered an issue when attempting to render a component that includes another component with content, only to have the subcomponent's content fail to render. F ...

Implement handleTextChange into React Native Elements custom search bar component

I need help with passing the handleTextChange function in the SearchBarCustom component. When I try to remove onChangeText={setValue} and add onchange={handleTextChange}, I am unable to type anything in the search bar. How can I successfully pass in the ...

What is the process of using observables in Angular to retrieve a number or variable?

While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that wh ...

Instructions on exporting binary data to a PNG file using nodejs

How can I convert a binary nodejs Buffer object containing bitmap information into an image and save it to a file? Edit: I attempted using the filesystem package as suggested by @herchu, but when I tried the following code: let robot = require("robotjs" ...

Is it possible for a button to simultaneously redirect and execute a function using asynchronous JavaScript?

After browsing through several related posts, I realized that most of them were using href to redirect to a completely new webpage. However, in my JavaScript code, I have a button that utilizes the Material-UI <Link>. <Button component={Link} to= ...

What is the method to prevent the label from closing in the MUI 5 datepicker?

Is there a method to prevent the Material 5 Datepicker from closing when there's a label but no value? Current Scenario: Current Desired Outcome: Expected Sample Code: <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker lab ...

Is it possible to bypass the confirmation page when submitting Google Form data?

Is there a way to bypass the confirmation page that appears after submitting a form? What I would like is for the form to simply refresh with empty data fields and display a message saying "your data has been submitted" along with the submitted data appea ...

The Date.UTC function is not providing the correct output

While attempting to change Unix timestamps into a more understandable format, I used Date.UTC(2017,09,23);. When running this code, it returned 1508716800000. However, upon verifying on the website , the displayed result showed October 23, 2017 instead o ...

Substitute regular expressions with several occurrences by their respective capture groups

I am attempting to use JavaScript to extract only the link text from a string and remove the href tags. The expected behavior is as shown below: <a href='www.google.com'>google</a>, <a href='www.bing.com'>bing</a> ...

Display message in a modal using React or JavaScript

Here's a puzzling query I have: Users can upload .MSG files to our system, and the BASE64 data is stored in the database. Now, I'm trying to incorporate these .MSG files into a model but facing conversion issues with BASE64 data. Interestingly, I ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

Is using the new Date function as a key prop in React a good

In my React code, I have been using new Date().getTime() as key props for some Input components. This may not be the best practice as keys should ideally be stable. However, I am curious to know why this approach is causing issues and why using Math.random ...

Arrange the columns in the Table in both ascending and descending order

While working on my React and MUI Table project, I encountered an issue with implementing sorting functionality for each column in both ascending and descending order. Whenever I click on the header to sort a column, an error message saying "Data is not it ...

"Troubleshooting Image Loading Issues in Next.js: A Guide to Reloading Unresponsive

Hello, I am facing an issue with rendering 300 images from IPFS data. Occasionally, around 3-4 of the images fail to load and result in a 404 error. Even after refreshing the page, these unloaded images remain inaccessible. It seems like they are permanent ...

Creating HTML elements using JavaScript compared to importing an HTML fileIn JavaScript,

I am currently in the process of building a website that is entirely driven by JavaScript. Aside from the index page, I do not use any HTML pages at all. Instead, I fetch JSON data for every query and then dynamically generate HTML within the JavaScript to ...

Adding an active class to a selected list item can easily be accomplished by targeting the

Hey there, I'm attempting to apply a class to the selected list item and also add a class when scrolling to a specific div. For instance, if I scroll to div#six, the number six (6) in the menu should also have the 'active' class. [Check out ...

Executing an Ajax callback function to navigate to a different page

I must handle ajax errors globally by capturing 901 error codes in my header.jsp. There is an error message displayed in the browser console: GET https://localhost:8443/SSApp/Pan/report?&vessel…namax%20Tanker%20Pool%20Limited&rptTitle=Activit ...