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