2
votes

I have to use push notifications in my app, so I followed this tutorial to add the ionic native push.

When I run the app on Android console prints this warning message:

Native: tried calling PushNotification.init, but the PushNotification plugin is not installed.

I have installed the module with:

$ ionic cordova plugin add phonegap-plugin-push

$ npm install --save @ionic-native/push

How can it be?


My code here:

I added the provider to my app.module.ts:

import { Push } from '@ionic-native/push';
...
providers: [
    StatusBar,
    SplashScreen,
    Services,
    Globals,
    Push,
    Globalization,
    Facebook,
    GoogleMaps,
    Geolocation,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    { provide: LOCALE_ID, useValue: 'es' },
    { provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig }
  ]

And in my app.component.ts I have this:

import { Component } from '@angular/core';
import { Platform, ModalController, MenuController, App, AlertController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Push, PushObject, PushOptions } from '@ionic-native/push';

import { TabsPage } from '../pages/tabs/tabs';
import { LogregPage } from '../pages/logreg/logreg';
import { FavoritosPage } from '../pages/favoritos/favoritos';
import { MaptestPage } from '../pages/maptest/maptest';

import { Globals } from '../providers/globals';
import { Services } from '../providers/services';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any;
  // rootPage:any = TabsPage;
  // rootPage:any = LogregPage;

  constructor(public appCtrl: App, public platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, public modalCtrl: ModalController,
      private push: Push, public menuCtrl: MenuController, public globals: Globals, private services: Services, public alertCtrl: AlertController) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

      /// Here we try to start the push services
      this.initPushNotification();

      /// This checks if user session is open
      this.globals.checkSession(
        (checked) : void => {
          if ( checked ) {
            this.rootPage = TabsPage;
          } else {
            this.rootPage = LogregPage;
          }
        }
      );

    });
  }

  /**
   * This method is the same as the example :)
   *
   */
  initPushNotification() {
    if (!this.platform.is('cordova')) {
      console.warn('Push notifications not initialized. Cordova is not available - Run in physical device');
      return;
    }
    const options: PushOptions = {
      android: {
        senderID: 'YOUR_SENDER_ID'
      },
      ios: {
        alert: 'true',
        badge: false,
        sound: 'true'
      },
      windows: {}
    };
    const pushObject: PushObject = this.push.init(options);

    pushObject.on('registration').subscribe((data: any) => {
      console.log('device token -> ' + data.registrationId);
      //TODO - send device token to server
    });

    pushObject.on('notification').subscribe((data: any) => {
      console.log('message -> ' + data.message);
      //if user using app and push notification comes
      if (data.additionalData.foreground) {
        // if application open, show popup
        let confirmAlert = this.alertCtrl.create({
          title: 'New Notification',
          message: data.message,
          buttons: [{
            text: 'Ignore',
            role: 'cancel'
          }, {
            text: 'View',
            handler: () => {
              //TODO: Your logic here
              console.log('Push notification recived');
            }
          }]
        });
        confirmAlert.present();
      } else {
        //if user NOT using app and push notification comes
        //TODO: Your logic on click of push notification directly
        
        console.log('Push notification clicked');
      }
    });

    pushObject.on('error').subscribe(error => console.error('Error with Push plugin' + error));
  }
}

EDIT:

After removing and then adding android platform, I get this error runing the app:

BUILD SUCCESSFUL

Total time: 3.207 secs
Subproject Path: CordovaLib
Starting a Gradle Daemon (subsequent builds will be faster)

+-----------------------------------------------------------------

| cordova-android-support-gradle-release: 26.+
+-----------------------------------------------------------------
The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
    at build_9ug1ggkhhrzygsw0k34tph6ua.run(/Users/[edited path]/platforms/android/build.gradle:143)

FAILURE: Build failed with an exception.

* Where:
Script '/Users/[edited path]/platforms/android/phonegap-plugin-push/tusclases-push.gradle' line: 35

* What went wrong:
A problem occurred evaluating root project 'android'.
> Failed to apply plugin [class 'com.google.gms.googleservices.GoogleServicesPlugin']
   > For input string: "+"

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.


BUILD FAILED

Total time: 5.408 secs
Error: /Users/[edited path]/platforms/android/gradlew: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* Where:
Script '/Users/[edited path]/platforms/android/phonegap-plugin-push/tusclases-push.gradle' line: 35

* What went wrong:
A problem occurred evaluating root project 'android'.
> Failed to apply plugin [class 'com.google.gms.googleservices.GoogleServicesPlugin']
   > For input string: "+"

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

[ERROR] An error occurred while running cordova run android (exit code 1).
1

1 Answers

2
votes

Hi if you want resolve this problem you must follow these instructions (windows10)

  1. ionic cordova platform rm android
  2. rm platform (platforms folder)
  3. rm plugin (plugins folder)
  4. ionic cordova platform add android
  5. ionic cordova build android

AND enjoy it !!!