首页 > 解决方案 > Xamarin Android Firebase 与 Azure 通知中心,应用程序关闭时注册密钥无效

问题描述

我的应用程序将在 GCM 注册令牌删除注册之前收到一条通知,并显示错误“注册的推送通知系统句柄不再有效”。我正在努力解决它丢失令牌的时间。如果我让应用程序保持打开状态,令牌仍然存在,当我关闭它时,我可以在令牌不再有效之前收到 1 条通知。我觉得它在途中某个地方失去了对令牌的引用,我不完全确定在哪里。

FireMessagingService 类:

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
const string TAG = "MyFirstBaseMessagingService";
private int Notification_ID = 2;
public override void OnMessageReceived(RemoteMessage message)
{
    try
    {
        Log.Debug(TAG, "From: " + message.From);
        if (message.GetNotification() != null)
        {
            Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
            SendNotification(message.Data);
        }
        else
        {
            SendNotification(message.Data);
        }
    } catch (Exception e)
    {

    }
}

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

        Drawable drawable = ContextCompat.GetDrawable(this, Resource.Drawable.lsbu);
        Bitmap bitmap = ((BitmapDrawable)drawable).Bitmap;

        string title = message["title"];
        string body = message["body"];

        NotificationManager notificationManager = GetSystemService(NotificationService) as NotificationManager;
        string ChannelID = GetString(Resource.String.LocalChannelID);
        string AppName = GetString(Resource.String.AppName);
        NotificationImportance Importance = NotificationImportance.Default;
        NotificationChannel mChannel = new NotificationChannel(ChannelID, AppName, Importance);
        notificationManager.CreateNotificationChannel(mChannel);

        Notification.Builder builder = new Notification.Builder(this, ChannelID)
                .SetWhen(DateTime.Now.Millisecond)
                .SetSmallIcon(Resource.Drawable.miniwozzad)
                .SetLargeIcon(bitmap)
                .SetContentTitle(title)
                .SetContentIntent(pendingIntent)
                .SetContentText(body)
                .SetChannelId(ChannelID);

        var notification = builder.Build();
        notificationManager.Notify(Notification_ID, notification);
        Notification_ID++;
    } catch (Exception e)
    {
        Console.WriteLine($"Error: {e.Message}");
    }
  }
}

还有我的 FirebaseRegistration 类:

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

public MyFirebaseIIDService()
{
    OnTokenRefresh();
}

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

void SendRegistrationToServer(string token)
{
    Task.Run(() =>
    {
        try
        {
            NotificationHub hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, this.ApplicationContext);

            var tags = new List<string>() { };
            var registration = hub.Register(token, tags.ToArray());
            var regID = registration.RegistrationId;
            Log.Debug(TAG, $"Successful registration of ID {regID}");
        }
        catch (Exception e)
        {

        }
    });
  }
}

最后是我的 AndroidManifest.xml

<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>

我最后在 MainActivity 中启动服务,每当我启动应用程序时,我都会在控制台中获得一个令牌,所以我知道我得到了一个令牌。任何有关我关闭应用程序时令牌为何消失的帮助将不胜感激!

标签: androidazurefirebasexamarinnotifications

解决方案


推荐阅读