c# - 使用 Xamarin 将带有一些标签的设备再次注册到 azure 通知中心

标签 c# android azure xamarin notifications

我正在按照一系列教程来创建推送通知 Xamarin 应用(特别是针对 Android),以通过 Azure 通知中心Firebase< 接收通知/强>。 这是1st video代码是here in github 。 但我需要选择应用程序使用标签将设备注册到通知中心的时刻。 目前,它发生在 OnNewToken 中,但我需要让用户首先登录,或者通过输入提供标签,然后我才会有要注册的标签。

解决方案/Project.Android/Model/FirebaseMessagingServiceEx.cs

public override void OnNewToken(string token)
{
    base.OnNewToken(token);

    System.Diagnostics.Debug.WriteLine(token);

    var hub = new NotificationHub(
        Constants.HubName,
        Constants.HubConnectionString,
        MainActivity.Context);

    // register device with Azure Notification Hub using the token from FCM
    var registration = hub.Register(token, Constants.HubTagName);

    // Register template
    var pnsHandle = registration.PNSHandle;
    var templateReg = hub.RegisterTemplate(
        pnsHandle,
        "defaultTemplate",
        Template,
        Constants.HubTagName);

    var receiver = DependencyService.Get<INotificationsReceiver>();
    receiver.RaiseNotificationReceived("Ready and registered...");
}

我什至不明白OnNewToken何时被调用! 我尝试强制生成另一个 token 以再次运行 OnNewToken...但未成功。 我可以在检索用户标签后检索当前 token 以稍后执行 hub.Register 吗?我看到的所有示例都使用已弃用的代码。 还有其他选择吗? 谢谢。

最佳答案

不幸的是,Xamarin 的推送通知文档非常支离 splinter ,其中很多内容已被弃用/过时。一段时间以来,我一直在努力寻找获取设备 token 并向 Azure 通知中心注册的最新机制。

要获取设备 token ,您不应重写 OnNewToken。目前的首选机制如下:

  1. 在您的 Android 项目中,创建一个实现 Android.Gms.Tasks.IOnCompleteListener 的 C# 类:
/// <summary>
/// Wraps the native Android interface <see cref="IOnCompleteListener"/>,
/// which enables interaction with Promise-style async callbacks.
/// </summary>
public class GetFcmTokenSuccessHandler : Java.Lang.Object, IOnCompleteListener
{
    private readonly Action<string> _handleFcmTokenCallback;

    public GetFcmTokenSuccessHandler(Action<string> handleFcmTokenCallback)
    {
        _handleFcmTokenCallback = handleFcmTokenCallback;
    }

    /// <summary>
    /// Method invoked when the associated <see cref="Task"/> completes.
    /// </summary>
    /// <param name="result">The task that completed.</param>
    public void OnComplete(Task result)
    {
        if (result.IsComplete && result.IsSuccessful)
        {
            var token = result.Result.ToString();

            _handleFcmTokenCallback?.Invoke(token);
        }
        else if (result.IsComplete && result.Exception != null)
        {
            // Add error handling here
        }
    }

    #region Interface requiresments; irrelevant to implementation
    public JniManagedPeerStates JniManagedPeerState => JniManagedPeerStates.None;

    public void SetJniIdentityHashCode(int value) { }
    public void SetJniManagedPeerState(JniManagedPeerStates value) { }
    public void SetPeerReference(JniObjectReference reference) { }
    #endregion
}
  • 登录后,在您的 Android 项目中触发依赖项注入(inject)的平台特定服务中的以下代码:
  • await FirebaseMessaging.Instance
        .GetToken()
        .AddOnCompleteListener(new GetFcmTokenSuccessHandler(token =>
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                // Add error handling here
            }
    
            // Now create your NotificationHub and register with the token and any tags
        }));
    

    作为附录,如果在应用运行时的任何时候您需要再次注册,我建议您将设备 token 缓存在内存中,以便您可以再次检索它,而无需通过 FirebaseMessaging 实例。

    关于c# - 使用 Xamarin 将带有一些标签的设备再次注册到 azure 通知中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69394598/

    相关文章:

    c# - 如何根据索引替换字符串中的文本

    azure - Azure 上类似 PiCloud 的服务?

    c# - DataGridView HeaderCell 为数字类型时不显示值

    c# - 从属性返回字符串连接的最有效方法

    c# - 除了某些索引处的元素外,如何在列表上使用 foreach 循环?

    java - Jsoup:分别解析url链接

    android - 将 React-Native View 包含到现有的 Android 应用程序中

    安卓嵌套列表

    c# - 诊断更新 Azure 表的 C# 程序中的内存泄漏的策略

    c# - Azure Functions - 带文件的路由模板