capacitor-community / fcm

Enable Firebase Cloud Messaging for Capacitor apps
https://capacitor.ionicframework.com/docs/
MIT License
237 stars 83 forks source link

PushNotifications stop working after installing this plugin #87

Closed DDholiyan closed 2 years ago

DDholiyan commented 2 years ago

I am currently using ionic capacitor PushNotifications for Firebase cloud messaging. By the help of this I can get tokens. Now I want to send notifications to all app users so I decided to use topics.

For this, I installed community/FCM plugin.

I also made suggested changes in the MainActivity.java file, no error during app build.

But after installation this FCM plugin, PushNotifications(token) stop working.

Even below code starts always retuning false.

if (isPushNotificationsAvailable) {
      this.initPushNotifications();
    }

Here is my MainActivity.java file:-

package io.ionic.starter;

import com.getcapacitor.community.fcm.FCMPlugin;

import android.os.Bundle;

import com.getcapacitor.BridgeActivity;

import com.getcapacitor.Plugin;

import java.util.ArrayList;

public class MainActivity extends BridgeActivity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
      // Ex: add(TotallyAwesomePlugin.class);
      add(FCMPlugin.class);
    }});
  }
}

Here my fcm.service.ts File:-

import { Component, Injectable } from '@angular/core';
import { Capacitor } from '@capacitor/core';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';
import {
  ActionPerformed,
  PushNotificationSchema,
  PushNotifications,
  Token
} from '@capacitor/push-notifications';
// import { FCM } from '@capacitor-community/fcm';

const isPushNotificationsAvailable = Capacitor.isPluginAvailable('PushNotifications');

@Injectable({
  providedIn: 'root'
})

export class FcmService {

  public topicName = 'project';

  constructor(
    private router: Router,
    private storage: Storage
  ) { }

  initPush() {
    //This Plugin is not available on web

    if (isPushNotificationsAvailable) {
      this.initPushNotifications();
    }
  }
  // Request permission to use push notifications
  // iOS will prompt user and return if they granted permission or not
  // Android will just grant without prompting
  private initPushNotifications() {

    //console.log('Initializing HomePage');

    PushNotifications.requestPermissions().then(result => {
      if (result.receive === 'granted') {
        // Register with Apple / Google to receive push via APNS/FCM
        PushNotifications.register();
      } else {
        // Show some error
      }
    });

    PushNotifications.addListener('registration', (token: Token) => {
      alert('Push registration success, token: ' + token.value);
      //Store Devive Token in session variable
      this.storage.set("device_token", token.value);
      // FCM.getToken()
      //   .then((r) => alert(`Token ${r.token}`))
      //   .catch((err) => console.log(err));
      // now you can subscribe to a specific topic
      // FCM.subscribeTo({ topic: this.topicName })
      //   .then((r) => alert(`subscribed to topic`))
      //   .catch((err) => console.log(err));      
    });

    PushNotifications.addListener('registrationError', (error: any) => {
      //alert('Error on registration: ' + JSON.stringify(error));
    });

    PushNotifications.addListener(
      'pushNotificationReceived',
      (notification: PushNotificationSchema) => {
        //alert('Push received: ' + JSON.stringify(notification));
      },
    );

    PushNotifications.addListener(
      'pushNotificationActionPerformed',
      (notification: ActionPerformed) => {
        // alert('Push action performed: ' + JSON.stringify(notification));
        const data = notification.notification.data;
        //console.log('Action performed: ' + JSON.stringify(notification.notification));
        if (data.detailsId) {
          this.router.navigate(['/bid-project', data.detailsId]);
        }
      },
    );
  }
  //Reset all Badge count
  // resetBadgeCount() {
  //   PushNotifications.removeAllDeliveredNotifications();
  // }
  // move to fcm demo
  // subscribeTo() {
  //   PushNotifications.register()
  //     .then((_) => {
  //       FCM.subscribeTo({ topic: this.topicName })
  //         .then((r) => alert(`subscribed to topic ${this.topicName}`))
  //         .catch((err) => console.log(err));
  //     })
  //     .catch((err) => alert(JSON.stringify(err)));
  // }

  // unsubscribeFrom() {
  //   FCM.unsubscribeFrom({ topic: this.topicName })
  //     .then((r) => alert(`unsubscribed from topic ${this.topicName}`))
  //     .catch((err) => console.log(err));

  // }
}

After removing community plugin token generation started working as before. Please tell me what wrong is with my code.

stewones commented 2 years ago

hello there. it's impossible to know without a reproducible example, where we can download and try.

can you please try on both latest capacitor + plugin?

rbokajr commented 2 years ago

We're experiencing the same issue. I can't easily give you a reproducible example at the moment as we're heads down working on an alternative... which is frustrating, but necessary.

This seems to only be affecting Android.

I've replicated this by:

  1. Create new Ionic app
  2. Add PushNotifications plugin (as described in the docs).
  3. Test -- push notifications work as expected.
  4. Now, add the FCM plugin, following your directions in the docs.
  5. Use the same MainActivity.java code as above.
  6. Test -- launch the app, have it attempt to register and before getting anywhere, other Capacitor plugins generate Console Errors. E.g. "SplashScreen" plugin is not implemented on android. "PushNotifications" plugin is not implemented.

What I suspect, is that since Capacitor 3 has automatically started loading plugins, the old way (modifying MainActivity.java) is broken. This seems to also still be using InstanceID, which should(?) be fixed for any reasonably modern implementation to work. (Correct me if I'm wrong there... but I believe there's an open issue for that as well.)

stewones commented 2 years ago

Cap 3 doesn't require registering plugins on MainActivity anymore, so you can remove any reference there. (Take a look in the example app on this repo)

Also there's an issue with the push-notifications package.

See my comment for workaround https://github.com/ionic-team/capacitor-plugins/pull/395#issuecomment-918595296

rbokajr commented 2 years ago

@stewones - appreciate the input, work, and expedient response very much... this will work for us for now, I suppose we'll track it until it is merged in... hopefully they can handle that sooner than later!

stewones commented 2 years ago

should be fixed on latest plugin version v2.0.2