Android 未命中 FCM (FirebaseMessagingService) OnNewToken

use*_*298 9 c# android push-notification firebase xamarin.forms

我正在按照此页面上的说明创建推送通知。我实际上之前已经做过一次并且能够让它工作(几周前),花了一些时间,并且认为我现在应该再次完成该教程作为复习,出于某种原因,我可以'甚至没有获取代码来点击 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>
Run Code Online (Sandbox Code Playgroud)

应用程序常量

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)\"}}";
}
Run Code Online (Sandbox Code Playgroud)

Firebase服务

[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());
    }
}
Run Code Online (Sandbox Code Playgroud)

google-services.json
我刚刚从 Firebase 下载了此文件,将其添加到 Android 项目并将“构建操作”设置为 GoogleServicesJson。

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

Leo*_*SFT 10

请卸载您的 Android 中的应用程序,然后重新部署它。

onNewToken()每次安装仅调用一次。

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


Jee*_*aJP 6

你忘了[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
    {
Run Code Online (Sandbox Code Playgroud)

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