Search code examples
c#firebasexamarin.androidfirebase-cloud-messagingproguard

Which proguard configuration is missing for firebase messaging to work on Xamarin.Android?


I've a Xamarin forms app packed for Android that I have deployed on the play store already. I tried "SDK assemblies only" for the linking along with the following proguard.cfg file:

-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**
-keep class com.google.gms.** { *; }
-dontwarn com.google.gms.**
-keep class com.google.firebase.** { *; }
-dontwarn com.google.firebase.**
-keep class android.support.v7.widget.** { *; }
-dontwarn android.support.v7.widget.*
-keep class android.support.v4.widget.Space { *; }
-dontwarn android.support.v4.widget.Space

I've noted that the app works fine overall but Firebase never gives a token back to the app with this config. I am using the following implementation of FirebaseMessagingService and in my case OnNewToken(string) is never called:

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
    public MyFirebaseMessagingService()
    {

    }
    public override async void OnNewToken(string token)
    {
        try
        {
            await SecureStorage.SetAsync("fcm_token", token);
        }
        catch (Exception e)
        {
            // Possible that device doesn't support secure storage on device.
        }
    }
    public override void OnMessageReceived(RemoteMessage p0)
    {
        base.OnMessageReceived(p0);
        new NotificationHelper().CreateNotification(p0.Data);
    }

}

The app works perfectly in debug mode and in release with Linking option set to "None" - Which is what I have currently on the play store so the app works at least... But obviously I would like make it cleaner and I am pretty sure I am not far from it.

I've no more errors/warnings and I also tried to set the Ignore linking for assemblies: Xamarin.Firebase.Common;Xamarin.Firebase.Iid;Xamarin.Firebase.Messaging but that didn't help.

What am I missing here in order to make firebase messaging works with linking set to "SDK assemblies only"?


Solution

  • The linker will sometimes remove code that you want to preserve.

    You could use the Android.Runtime.Preserve attribute.

    public class Example
    {
        [Android.Runtime.Preserve]
        public Example ()
        {
        }
    }
    

    For more details, please check the link below. https://learn.microsoft.com/en-us/xamarin/android/deploy-test/linker