【问题标题】:FCM (FirebaseMessagingService) OnNewToken not being hit with AndroidFCM(FirebaseMessagingService)OnNewToken 没有被 Android 击中
【发布时间】:2020-06-07 17:32:53
【问题描述】:

我正在按照this page 上的说明创建推送通知。我之前实际上已经做过一次并且能够让它工作(几周前),花了一些时间,我想我现在才再次做这个教程作为复习,出于某种原因,我可以'甚至无法获取代码来点击 OnNewToken 方法来生成我的令牌并将设备注册到通知中心。

我看了几十个视频,阅读了其他教程,他们都在说/展示几乎相同的东西,所以我想我需要一双新的眼睛来告诉我我第二次错过了什么.

我已尝试提取特定信息,但仍尽可能保持其可读性。

已安装的 NuGet 包:

  1. Xamarin.Firebase.Messaging - v71.1740.0
  2. Xamarin.GooglePlayServices.Base - v71.1610.0
  3. Xamarin.Forms - v4.4.0.991640

Android 项目中的文件
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="(my firebase package / project package name)" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<!--
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
-->
<application>
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="${applicationId}" />
        </intent-filter>
    </receiver>
</application>
</manifest>

AppConstants

public static class AppConstants
{
    public static string NotificationChannelName { get; set; } = "XamarinNotifyChannel";
    public static string NotificationHubName { get; set; } = "(my azure notification hub name)";
    public static string ListenConnectionString { get; set; } = "(my default listen shared access signature from azure portal)";
    public static string DebugTag { get; set; } = "XamarinNotify";
    public static string[] SubscriptionTags { get; set; } = { "default" };
    public static string FCMTemplateBody { get; set; } = "{\"data\":{\"message\":\"$(messageParam)\"}}";
    public static string APNTemplateBody { get; set; } = "{\"aps\":{\"alert\":\"$(messageParam)\"}}";
}

FirebaseService

[Service(Name = "(my package name).MyFirebaseMessagingService")]
[IntentFilter(new[] {  "com.google.firebase.MESSAGING_EVENT" })]
public class FirebaseService : FirebaseMessagingService
{
    public override void OnNewToken(string token)
    {
        base.OnNewToken(token);
        Console.WriteLine("NEW_TOKEN", token);
        SendRegistrationToServer(token);
    }

    void SendRegistrationToServer(string token)
    {
        NotificationHub hub = new NotificationHub(AppConstants.NotificationHubName, AppConstants.ListenConnectionString, this);
        // register device with Azure Notification Hub using the token from FCM
        Registration reg = hub.Register(token, AppConstants.SubscriptionTags);
        // subscribe to the SubscriptionTags list with a simple template.
        string pnsHandle = reg.PNSHandle;
        hub.RegisterTemplate(pnsHandle, "defaultTemplate", AppConstants.FCMTemplateBody, AppConstants.SubscriptionTags);
    }

    public override void OnMessageReceived(RemoteMessage message)
    {
        base.OnMessageReceived(message);
        string messageBody = string.Empty;
        if (message.GetNotification() != null)
        {
            messageBody = message.GetNotification().Body;
        }
        else
        {
            messageBody = message.Data.Values.First();
        }
        try
        {
            MessagingCenter.Send(messageBody, "Update");
        }
        catch (Exception e)
        { }
        SendLocalNotification(messageBody);
    }

    void SendLocalNotification(string body)
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        intent.PutExtra("message", body);

        //Unique request code to avoid PendingIntent collision.
        var requestCode = new Random().Next();
        var pendingIntent = PendingIntent.GetActivity(this, requestCode, intent, PendingIntentFlags.OneShot);

        var notificationBuilder = new NotificationCompat.Builder(this)
            .SetContentTitle("XamarinNotify Message")
            .SetSmallIcon(Resource.Drawable.ic_launcher)
            .SetContentText(body)
            .SetAutoCancel(true)
            .SetShowWhen(false)
            .SetContentIntent(pendingIntent);

        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            notificationBuilder.SetChannelId(AppConstants.NotificationChannelName);
        }

        var notificationManager = NotificationManager.FromContext(this);
        notificationManager.Notify(0, notificationBuilder.Build());
    }
}

google-services.json
我刚刚从 Firebase 下载了这个文件,将它添加到 Android 项目中并将 Build Action 设置为 GoogleServicesJson。

希望有人能看到我缺少的东西,因为我以前也有过同样的教程。

【问题讨论】:

  • 请在您的android中卸载该应用程序,然后重新部署它。 onNewToken() 每次安装只会调用一次。如果您需要再次调用它,请从您的设备中卸载该应用并重新启动它。
  • @LeonLu-MSFT 我很确定这成功了 :) 我实际上是在回家的路上考虑的,然后看到了你的评论。
  • 我可以移到评论上方回答吗?并标记它,它将帮助其他有类似问题的人。
  • @LeonLu-MSFT 是的,当然
  • 希望这也适用于我的情况

标签: c# android firebase xamarin.forms push-notification


【解决方案1】:

你忘了[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]

[Service()]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class FirebaseService : FirebaseMessagingService
    {

【讨论】:

  • 很高兴听到这个消息!
  • 谢谢!这为我解决了。回顾: 1. 确保您拥有正确的 google-services.json 文件并将 Build Action 设置为 GoogleServicesJson 2. 确保您的 AppManifest.xml 已更新,特别检查 package 属性 3. 确保您将 [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })] 设置为这个答案解释了 4. 确保 Firebase 配置正确 5. 重新安装您的应用程序以获取新令牌
【解决方案2】:

请在您的安卓系统中卸载该应用程序,然后重新部署。

onNewToken() 每次安装只会调用一次。

如果您需要再次调用它,请从您的设备中卸载该应用并重新启动它。

【讨论】:

  • 这可能并不总是可行的,如果推送通知作为更新的一部分启用,我们必须要求所有用户重新安装应用程序?
  • 我已经声明了 ``` [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })] [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })] ``` 上面我的类并卸载并重新安装了应用程序(卸载前还清除了应用程序数据)但我的 onnewtoken() 仍然没有被调用。
【解决方案3】:

经过两天的故障排除,我终于发现以下 nuget 包的最新版本(或可能是其中之一)导致了这种情况。我降级到以下版本并开始工作。

Xamarin.Azure.NotificationHubs.Android -> v0.6.0
Xamarin.Firebase.Messaging -> v71.1740.0
Xamarin.GooglePlayServices.Base -> v71.1610.0

【讨论】:

    猜你喜欢
    • 2019-08-31
    • 2020-04-17
    • 2017-08-24
    • 2018-12-08
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    相关资源
    最近更新 更多