FCM - Android Xamarin NotRegistered error when sending message after re-debugging the App

后端 未结 2 811
故里飘歌
故里飘歌 2021-01-07 00:47

I am developing an App in Xamarin Android, for notifications I am using FCM the Pre-Release package: https://www.nuget.org/packages/Xamarin.Firebase.Messaging/

Now e

相关标签:
2条回答
  • 2021-01-07 01:12

    As this issue only happens when running the Application from Visual Studio while debugging the application (not in the version deployed to PlayStore), what I did to solve the issue temporarily is I created the following service:

        [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);
                }
            }
        }
    

    then in my launch Activity (the activity that loads whenever the Application is opened is do the following:

    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
    
    }
    

    This will unregister your existing FCMToken and will refresh the Token, so the OnTokenRefresh method will be called, then you will have to write some logic to update the FCMToken on the server.

    [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();
        }
    }
    
    0 讨论(0)
  • 2021-01-07 01:16

    i'm manualy trying to initialize like this

     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
            }
    

    So when user opens the app, I'm trying to reinitialize the Firebase app. If it is already initalized it will throw an exception :) I'm taking the token there so it gives me the active registered token. If app is not initialized everything will work on smoothly and so your OnTokenRefresh method will be fired as expected. Hope this helps you.

    0 讨论(0)
提交回复
热议问题