Search code examples
androidfirebase.net-corefirebase-cloud-messagingmaui

Can't change background color of Android notification using Firebase and dotnet Maui


I am using Firebase to send push notifications to a .NET8 MAUI app... The notifications work, but the background color of the notification shows as a very light grey, making it impossible to see the icon (pictures included below)...

There is supposedly a workaround to add a line to the AndroidManifest.xml file, but that doesn't appear to fix the problem.....

Here is the relevant part of my code:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.mycompany.myapp">
    <application android:icon="@mipmap/appicon">

        <!-- sets the icon, which it is doing correctly. -->
        <meta-data 
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/push_notification_icon" />

        <!-- This should set the background color of the icon when you swipe down, 
             but it doesnt seem to work -->
        <meta-data 
            android:name="com.google.firebase.messaging.default_notification_color" 
            android:resource="@color/default_notification_color"
            tools:replace="android:resource" />

        <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>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
</manifest>

Platforms\Android\Resources\values\colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="default_notification_color">#FF0000</color>
</resources>

MauiProgram.cs

using Plugin.Firebase.Auth;
using Plugin.Firebase.Bundled.Shared;

#if IOS
using Plugin.Firebase.Bundled.Platforms.iOS;
#elif ANDROID
using Plugin.Firebase.Bundled.Platforms.Android;
#endif

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        return MauiApp
            .CreateBuilder()
            .UseMauiApp<App>()
            .UseMauiCompatibility()
            .UseMauiCommunityToolkit()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            })
            .RegisterFirebaseServices()
            .Build();
    }

    private static MauiAppBuilder RegisterFirebaseServices(this MauiAppBuilder builder)
    {
        builder.ConfigureLifecycleEvents(events =>
        {
#if IOS
            events.AddiOS(iOS => iOS.FinishedLaunching((app, launchOptions) => {
                CrossFirebase.Initialize(CreateCrossFirebaseSettings());
                return false;
            }));
#elif ANDROID
            events.AddAndroid(android => android.OnCreate((activity, _) =>
                CrossFirebase.Initialize(activity, CreateCrossFirebaseSettings())
            ));
#endif
        });
        builder.Services.AddSingleton(_ => CrossFirebaseAuth.Current);
        return builder;
    }

    private static CrossFirebaseSettings CreateCrossFirebaseSettings()
    {
        return new CrossFirebaseSettings(
            isAuthEnabled: true,
            isCloudMessagingEnabled: true,
            isAnalyticsEnabled: false);
    }
}

Platforms\Android\MainActivity.cs

using Plugin.Firebase.CloudMessaging;

[Activity(Label = "MyApp", Theme = "@style/Maui.SplashTheme", MainLauncher = true)]
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        if (OperatingSystem.IsAndroidVersionAtLeast(33))
        {
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.PostNotifications) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.PostNotifications }, 0);
            }
        }

        HandleIntent(Intent);
        CreateNotificationChannelIfNeeded();
    }

    protected override void OnNewIntent(Intent intent)
    {
        base.OnNewIntent(intent);
        HandleIntent(intent);
    }

    private static void HandleIntent(Intent intent)
    {
        FirebaseCloudMessagingImplementation.OnNewIntent(intent);
    }

    private void CreateNotificationChannelIfNeeded()
    {
        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            CreateNotificationChannel();
        }
    }

    private void CreateNotificationChannel()
    {
        if (OperatingSystem.IsAndroidVersionAtLeast(26))
        {
            var channelId = $"{PackageName}.general";
            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            var channel = new NotificationChannel(channelId, "General", NotificationImportance.Default);
            notificationManager.CreateNotificationChannel(channel);
            FirebaseCloudMessagingImplementation.ChannelId = channelId;
            FirebaseCloudMessagingImplementation.SmallIconRef = Resource.Drawable.push_notification_icon;
        }
    }
}

MyApp.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net8.0-ios;net8.0-android</TargetFrameworks>
    <OutputType>Exe</OutputType>
    <UseMaui>true</UseMaui>
    <!-- lots more here removed -->
  </PropertyGroup>
  
  <ItemGroup>
    <!-- App Icon -->
    <MauiIcon Include="Resources\AppIcon\appicon.png" BaseSize="48,48" Color="#01CAFF" />
    <!-- Images -->
    <MauiImage Include="Resources\Images\*" />
  </ItemGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net8.0-android'">
    <GoogleServicesJson Include="Platforms\Android\google-services.json" />
    <PackageReference Include="Xamarin.AndroidX.Core" Version="1.12.0.3" />
    <PackageReference Include="Xamarin.AndroidX.Collection" Version="1.3.0.2" />
    <PackageReference Include="Xamarin.AndroidX.Collection.Ktx" Version="1.3.0.2" />
    <PackageReference Include="Xamarin.AndroidX.Activity.Ktx" Version="1.8.1.1" />
    <PackageReference Include="Xamarin.Google.Android.Material" Version="1.10.0.2" />
  </ItemGroup>
  <ItemGroup>
    <MauiImage Update="Resources\Images\push_notification_icon.png" Resize="false" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="CommunityToolkit.Maui" Version="9.0.3" />
    <PackageReference Include="ExifLib.Standard" Version="1.7.0" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
    <PackageReference Include="Microsoft.Extensions.Http.Polly" Version="8.0.8" />
    <PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="8.8.0" />
    <PackageReference Include="Plugin.Firebase" Version="3.0.0" />
    <PackageReference Include="Xamarin.Build.Download" Version="0.11.4" />
  </ItemGroup>

  </ItemGroup>
  <ItemGroup>
    <None Update="Resources\Raw\app_store_logo128x128.png">
      <Pack>True</Pack>
      <PackagePath>\</PackagePath>
    </None>
  </ItemGroup>
</Project>

I also obviously have my google-services.json file in there as well and the app created in the Firebase console....

When I send a test message from the console, the notification comes through. BUT, you will see when I swipe down, the icon background is nearly white.

Here is my icon file

Here is the notification prior to swiping down. Looks beautiful!!!

enter image description here

Here is my notification when I swipe down, but you can barely see the icon because the background color is so light:

enter image description here

Any ideas at all?????


Solution

  • Still not sure why this wasn't working, but something was wrong with the png file I was using. I created another PNG file - changed nothing else - and it started to work. No idea what was wrong with the first file, but it is working now....