简体   繁体   English

使用Xamarin.Forms和Azure推送通知:设备未注册

[英]Push notification with Xamarin.Forms and Azure: the devices are not registered

I followed the following tutorial step by step: https://docs.microsoft.com/it-it/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm 我一步一步地遵循了以下教程: https : //docs.microsoft.com/it-it/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm

I started the Android app on a physical device with Android 8.0.0. 我在装有Android 8.0.0的物理设备上启动了Android应用程序。 Then also on 3 emulators (API 23, 25 and 27). 然后在3个仿真器上(API 23、25和27)。

In the Azure control panel, the registered devices are always zero. 在Azure控制面板中,注册的设备始终为零。 As a result, the sending test is successful, but no notification arrives on the devices (" Message was successfully sent, but there were no matching targets "). 结果,发送测试成功,但是没有通知到达设备(“ 消息已成功发送,但是没有匹配的目标 ”)。

I skipped a few steps concerning the registration of devices? 我跳过了有关设备注册的几个步骤?

* Code integration * ***[start code] *代码集成* *** [起始代码]

MainActivity.cs MainActivity.cs

namespace test021_push.Droid
{
    [Activity(Label = "test021_push", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public const string TAG = "MainActivity";

        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            //push notification
            if (Intent.Extras != null)
            {
                foreach (var key in Intent.Extras.KeySet())
                {
                    if (key != null)
                    {
                        var value = Intent.Extras.GetString(key);
                        Log.Debug(TAG, "Key: {0} Value: {1}", key, value);
                    }
                }
            }

            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
    }
}

Constants.cs Constants.cs

namespace test021_push.Droid
{
    public static class Constants
    {
        public const string ListenConnectionString = "Endpoint=sb://namespacepodo.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=lN8fZnQYlYQ/ELVrgnzUD16MBw9bOTH/Yxaw2LANA58=";
        public const string NotificationHubName = "notificationHubPodo";
    }
}

MyFirebaseIIDService.cs MyFirebaseIIDService.cs

namespace test021_push.Droid
{
    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseIIDService : FirebaseInstanceIdService
    {
        const string TAG = "MyFirebaseIIDService";
        NotificationHub hub;

        public override void OnTokenRefresh()
        {
            var refreshedToken = FirebaseInstanceId.Instance.Token;
            Log.Debug(TAG, "FCM token: " + refreshedToken);
            SendRegistrationToServer(refreshedToken);
        }

        void SendRegistrationToServer(string token)
        {
            // Register with Notification Hubs
            hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, this);

            var tags = new List<string>() { };
            var regID = hub.Register(token, tags.ToArray()).RegistrationId;

            Log.Debug(TAG, $"Successful registration of ID {regID}");
        }
    }
}

MyFirebaseMessagingService.cs MyFirebaseMessagingService.cs

namespace test021_push.Droid
{
    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class MyFirebaseMessagingService : FirebaseMessagingService
    {
        const string TAG = "MyFirebaseMsgService";
        public override void OnMessageReceived(RemoteMessage message)
        {
            Log.Debug(TAG, "From: " + message.From);
            if (message.GetNotification() != null)
            {
                //These is how most messages will be received
                Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
                SendNotification(message.GetNotification().Body);
            }
            else
            {
                //Only used for debugging payloads sent from the Azure portal
                SendNotification(message.Data.Values.First());

            }

        }

        void SendNotification(string messageBody)
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            //var notificationBuilder = new Notification.Builder(this)  //Notification.Builder è deprecato
            var notificationBuilder = new NotificationCompat.Builder(this)
                        .SetContentTitle("FCM Message")
                        .SetSmallIcon(Resource.Drawable.ic_launcher)
                        .SetContentText(messageBody)
                        .SetAutoCancel(true)
                        .SetContentIntent(pendingIntent);

            var notificationManager = NotificationManager.FromContext(this);

            notificationManager.Notify(0, notificationBuilder.Build());
        }
    }
}

***[end code] *** [结束代码]

Now notifications arrive only on a device (emulator Android API 25). 现在,通知仅到达设备(模拟器Android API 25)上。 In the other emulators (APIs 23 and 27) and in the physical device, nothing happens . 在其他仿真器(API 23和27)以及物理设备中,什么也没有发生。 Despite having done the exact same procedure on all 4 devices. 尽管在所有4个设备上都执行了完全相同的过程。

And on Azure I see 3 registered devices.. 在Azure上,我看到3个注册的设备。

Thank you very much for your answers. 非常感谢您的回答。

Have you checked in the firebase console if the devices are being registred? 您是否已在Firebase控制台中检查是否正在注册设备?

Also check the log while starting the app. 在启动应用程序时,还要检查日志。 It is possible that registering at firebase fails. 在Firebase上注册可能会失败。 Just search the logs for "firebase". 只需在日志中搜索“ firebase”即可。 Also try adding a breakpoint in OnTokenRefresh() 还可以尝试在OnTokenRefresh()添加断点

If this fails, it could be that your google-services.json is wrong or has the wrong Build Action. 如果失败,则可能是您的google-services.json错误或构建操作错误。

Edit: The Azure docs are outdated. 编辑:Azure文档已过时。 Android 8.0 added the Notification channel feature. Android 8.0添加了“通知频道”功能。 And you have to use it, otherwise the Notification will not be shown. 而且您必须使用它,否则通知将不会显示。 This however fixes only displaying the notification. 但是,此操作仅修复了显示通知的问题。 If the notification does not arrive in OnMessageReceived(RemoteMessage message) there is another bug. 如果通知未到达OnMessageReceived(RemoteMessage message)则存在另一个错误。

I solved it like this in the SendNotification method 我在SendNotification方法中像这样解决了它

        var channelId = "testChannelId";
        var channelDescription = "Test Description";

        var builder = Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O
            ? new Notification.Builder(Android.App.Application.Context, channelId)
            : new Notification.Builder(Android.App.Application.Context);

        var notification = builder
                    .SetContentTitle("Test")
                    .SetContentText(messageBody)
                    .SetSmallIcon(Resource.Drawable.ic_notification)
                    .SetAutoCancel(true)
                    .SetWhen(DateTime.Now.ToUnixMillisecondTime())
                    .SetShowWhen(true)
                    .Build();
        var notificationManager = NotificationManager.FromContext(Application.Context);

        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            var channel = new NotificationChannel(channelId,
                    channelDescription,
                    NotificationImportance.Default);
            notificationManager.CreateNotificationChannel(channel);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM