I am converting a GCM-based messaging app to firebase. Messages are being sent to the app using the data-payload format. If my app is running, either in the foreground or background, the code in OnMessageRecieved runs and sets the notification title. But if the app is not running when the notification is recieved it does not display a title. I have tried adding a title to the data payload:
{
"data": {
"title": "My Title",
"message": "Text of the message",
}
}
and also have tried defining it in the AndroidManifest.xml following the format of defining the icon:
<meta-data android:name="com.google.firebase.messaging.default_notification_title" android:value="My Title"/>
but neither of these methods have worked.
public override void OnMessageReceived(RemoteMessage message)
{
try
{
SendNotification(message.GetNotification()?.Body, message.Data);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
void SendNotification(string messageBody, IDictionary<string, string> data)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
foreach (string key in data.Keys)
{
if (key == "message")
messageBody = data[key];
else
intent.PutExtra(key, data[key]);
}
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Notification.Builder(this)
.SetSmallIcon(Resource.Drawable.smallicon)
.SetContentTitle(AppInfo.DisplayName)
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
Turns out OnMessageRecieved IS being run, the issue was with the setting of the title itself:
.SetContentTitle(AppInfo.DisplayName)
AppInfo.DisplayName is set in the OnCreate method of MainActivity. I replaced the variable with:
.SetContentTitle(ApplicationInfo.LoadLabel(PackageManager))
and that displays the app name as the title in notifications that are received when the app is not running. Thanks BobSnyder for pointing me in the right direction!