xamarin android通知中心到特定设备

问题描述

我正在按照本教程测试适用于android的通知中心,它的工作原理 Graph

但是我需要完成用户注册过程并获取用户ID,以便可以将用户ID用作标记在Azure通知中心进行注册。因此,我没有立即在class CreateMyModelView(LoginrequiredMixin,CreateView): model = MyModel template_name = 'myapp/create-my-model.html' form_class = CreateMyModelForm success_url = reverse_lazy('myapp:mypage') def form_valid(self,form): # You can modify the object-to-be-saved before saving,e.g. # form.instance.creator = self.request.user # The CreateView implementation just calls `form.save()` and redirects away,# so let's reuse that. return super().form_valid(form) 中进行注册,而是将令牌保存在数据库中。

所以不要这样

MainAcitivty.cs

我只是将令牌插入本地数据库

public override void OnNewToken(string token)
        {
            Log.Debug(TAG,"FCM token: " + token);
            SendRegistrationToServer(token);
        }

整个注册过程完成后,我在public override void OnNewToken(string token) { Log.Debug(TAG,"FCM token: " + token); LocalDb.InsertDevicetoken(token); } 中关注了

RegistrationAcitivty.cs

以下是NotificationUtil.cs的代码

 var notificationUtil = new NotificationUtil();
 notificationUtil.SendRegistrationToServer(this.ApplicationContext);

我只能猜测我在这里使用了正确的上下文对象,当我运行代码时,我遇到了以下异常

using System;
using System.Collections.Generic;
using Android.Util;
using PantAppLib.source.dbaccess;
using PantAppLib.source.models;
using WindowsAzure.Messaging;

namespace PantAppAndroid.Utils
{
    public class NotificationUtil
    {
        public void SendRegistrationToServer(Android.Content.Context context)
        {
            try
            {
                // Register with Notification Hubs
                NotificationHub hub = new NotificationHub(Constants.NotificationHubName,Constants.ListenConnectionString,context);
                var userProfile = LocalDb.GetUserProfile();
                if (userProfile != null)
                {
                    var tags = new List<string>() { userProfile.Id };
                    var token = LocalDb.GetDevicetoken().TokenValue;
                    Registration registration = hub.Register(token,tags.ToArray());
                    var regID = registration.RegistrationId;

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

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}

后续教程-https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm不适用于xamarin android,因此我不确定如何以正确的方式进行操作。

解决方法

NetworkOnMainThreadException是关键,查看异常堆栈,NotificationHub.Register是您的问题,因为由于发生底层网络调用而无法在UI线程上执行,只需执行它即可在后台线程上。

示例:

~~~
Registration registration;
await Task.Run(() => registration = hub.Register(token,tags.ToArray()));
~~~