如何解决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()));
~~~
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。