FCM - Android Xamarin未注册错误发送消息后,重新调试应用程序

本文关键字:新调试 应用程序 调试 消息 Xamarin Android 注册 错误 FCM | 更新日期: 2023-09-27 18:18:27

我正在开发Xamarin Android的应用程序,对于通知,我使用FCM的预发布包:https://www.nuget.org/packages/Xamarin.Firebase.Messaging/

现在一切都很好,如果我清理应用程序数据,OnTokenRefresh事件被触发,并生成一个新的令牌-当我在这个令牌上发送一个新的通知时,通知被OnMessageReceived()中的设备发送和接收-

问题是当我对代码进行更改并再次运行应用程序时,如果我使用旧令牌,我在发送通知时得到NotRegistered错误,但如果我去清理应用程序数据,那么OnTokenRefresh()被触发,生成一个新的令牌-新的令牌工作。

类似的问题在这里,但这是GCM(我使用FCM):

Google cloud message 'Not Registered'失败和取消订阅最佳实践?

https://stackoverflow.com/a/36856867/1910735

https://forums.xamarin.com/discussion/65205/google-cloud-messaging-issues最新

My FCMInstanceIdService

[Service, IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class FCMInstanceIdService : FirebaseInstanceIdService
{
    private string Tag = "FCMInstanceIdService";
    public override void OnTokenRefresh()
    {
        var fcmDeviceId = FirebaseInstanceId.Instance.Token;
        if (Settings.DeviceId != fcmDeviceId)
        {
            var oldDeviceId = Settings.DeviceId;
            Settings.DeviceId = fcmDeviceId;
            //TODO: update token on DB - Currently OnTokenRefresh is only called when: 1. App data is cleaned, 2. The app is re-installed
            //_usersProvider.UpdateUserDeviceId(oldDeviceId, fcmDeviceId);
        }
        base.OnTokenRefresh();
    }
}

My Message Receive Service:

[Service, IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class FCMListenerService : FirebaseMessagingService
{
    private string Tag = "FCM_Listener_Service";
    public override void OnMessageReceived(RemoteMessage message)
    {
        base.OnMessageReceived(message);
        var notification = message.GetNotification();
        var data = message.Data;
        var title = notification.Title;
        var body = notification.Body;
        SendNotification(title, body);
    }
    private void SendNotification(string title, string body)
    {
        //TODO: Display notification to user
    }
}

清单:

<application android:label="TBApp" android:theme="@style/TBAppTheme">
<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>
</application>

我如何在调试模式下强制刷新FCM令牌,这样我就不必每次运行应用程序时都删除应用程序数据?

FCM - Android Xamarin未注册错误发送消息后,重新调试应用程序

由于此问题仅发生在调试应用程序时从Visual Studio运行应用程序时(不在部署到PlayStore的版本中),我所做的是暂时解决这个问题,我创建了以下服务:

    [Service]
    public class FCMRegistrationService : IntentService
    {
        private const string Tag = "FCMRegistrationService";
        static object locker = new object();
        protected override void OnHandleIntent(Intent intent)
        {
            try
            {
                lock (locker)
                {
                    var instanceId = FirebaseInstanceId.Instance;
                    var token = instanceId.Token;
                    if (string.IsNullOrEmpty(token))
                        return;
#if DEBUG
                    instanceId.DeleteToken(token, "");
                    instanceId.DeleteInstanceId();
#endif

                }
            }
            catch (Exception e)
            {
                Log.Debug(Tag, e.Message);
            }
        }
    }

然后在我的启动活动(每当应用程序打开时加载的活动)中执行以下操作:

protected override void OnCreate(Bundle savedInstanceState)
{
            base.OnCreate(savedInstanceState);

#if DEBUG
            if (!IsMyServiceRunning("FCMRegistrationService"))
            {
                var intent = new Intent(this, typeof(FCMRegistrationService));
                StartService(intent);
            }
            // For debug mode only - will accept the HTTPS certificate of Test/Dev server, as the HTTPS certificate is invalid /not trusted
            ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
#endif
}

这将注销您现有的FCMToken并刷新令牌,因此将调用OnTokenRefresh方法,然后您将不得不编写一些逻辑来更新服务器上的FCMToken。

[Service, IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class FCMInstanceIdService : FirebaseInstanceIdService
{
   // private string LogTag = "FCMInstanceIdService";
    public override void OnTokenRefresh()
    {
        var fcmDeviceId = FirebaseInstanceId.Instance.Token;
        // Settings (is Shared Preferences) - I save the FCMToken Id in shared preferences 
       // if FCMTokenId is not the same as old Token then update on the server
        if (Settings.FcmTokenId != fcmDeviceId)
        {
            var oldFcmId = Settings.FcmTokenId;
            var validationContainer = new ValidationContainer();
            // HERE UPDATE THE TOKEN ON THE SERVER
            TBApp.Current._usersProvider.UpdateFcmTokenOnServer(oldFcmId, fcmDeviceId, validationContainer);
            Settings.FcmTokenId = fcmDeviceId;
        }
        base.OnTokenRefresh();
    }
}

我手动尝试这样初始化

 var options = new FirebaseOptions.Builder()
             .SetApplicationId("YOURAPPID")
             .SetApiKey("YOURAPIKEY")
             //.SetDatabaseUrl(Keys.Firebase.Database_Url) //i'M not using it
             .SetGcmSenderId("YOURSENDERID")
    //.SetStorageBucket(Keys.Firebase.StorageBucket)//i'M not using it
    .Build();
        try
        {   //try to initilize firebase app to get token
            FirebaseApp.InitializeApp(Forms.Context, options);//initializeto get token
        }
        catch
        {   //if app already initialized it will throw exception, so get the previous active token and send to your server-database etc
            var instanceId = FirebaseInstanceId.Instance;
            var token = instanceId.Token;
            Service.MyFirebaseMessagingService.RegisterForAndroid(token); //this method sends the token to my server app, you have to write your own
        }

所以当用户打开应用程序时,我试图重新初始化Firebase应用程序。如果它已经初始化,它会抛出一个异常:)我在那里取令牌,所以它给了我活跃的注册令牌。如果应用程序没有初始化,一切都将顺利工作,所以你的OnTokenRefresh方法将按预期触发。