【问题标题】:Capacitor push notification and FCM generate different tokens, crashes android电容推送通知和 FCM 生成不同的令牌,导致 android 崩溃
【发布时间】:2022-01-04 15:38:56
【问题描述】:

带有电容推送通知和 FCM 插件的 Ionic 5 应用。

import { FCM } from '@capacitor-community/fcm';

import {
  ActionPerformed,
  PushNotificationSchema,
  PushNotifications,
  Token,
} from '@capacitor/push-notifications';

为什么它们都生成不同的令牌?

对于 Capacitor/PushNotifications,下面会生成一个令牌

PushNotifications.addListener('registration',
        async (token: Token) => {
          console.log('token: ' + token.value);
        }
      ).catch(e=>{alert('reqPerm'+e)});

而对于 FCM,以下生成不同的令牌

FCM.getToken()
      .then(async (r) => {
         console.log(`token saved ${r.token}`)
        })
      .catch((err) => console.warn('error saving token', err));

FCM 令牌在 iOS 上有效(iPhone 接收通知),但在 Android 上注册它时,它会说明已注册的令牌无效。所以我不得不为 Android 使用 PushNotifications.addListener 中的令牌,但是当它收到通知时,应用程序崩溃了。

我确保 google-services.json 文件位于 android/apps 文件夹中。

什么给了?有什么建议吗?

【问题讨论】:

  • iOS 上从registration 收到的令牌是 APN 令牌而不是 FCM。它没有记录,因此很容易混淆。对于您在 Android 上的崩溃,您可以使用 logcat 转储电话日志吗?

标签: android ionic-framework push-notification firebase-cloud-messaging capacitor


【解决方案1】:

是的,在新的更新中,FCM 正在返回 JWT 令牌。有一个与 iOS 相同的解决方法。您需要先注册才能获得令牌。

getToken() {
    PushNotifications.requestPermissions().then(async (permission) => {
        if (permission.receive == "granted") {
            // Register with Apple / Google to receive push via APNS/FCM
            if (Capacitor.getPlatform() == 'ios') {
                await PushNotifications.register();
                PushNotifications.addListener('registration', (token: Token) => {
                    FCM.getToken().then((result) => {
                        console.log(result.token); // This is token for IOS
                    }).catch((err) => console.log('i am Error', err));
                })
            } else if (Capacitor.getPlatform() == 'android') {
                await PushNotifications.register()
                PushNotifications.addListener('registration', async ({ value }) => {
                    let androidToken = value; // this is token for Android use this token
                });
            }
        } else {
            // No permission for push granted
            alert('No Permission for Notifications!')
        }
    });

}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多