I followed the tutorial to add push notifications to a Xamarin Forms app. It works in iOS in all states: app not running or running in the background or active. For android I get the notifications when the app is not running or it's in the background but not when the app is active.
I am using:
Xamarin.Azure.NotificationHubs.Android 1.1.4.1. (1/28/2021)
Xamarin.Firebase.Messaging 122.0.0 (6/11/2021)
Heres in my code on Android:
public class MainActivity : FormsAppCompatActivity
{
internal static readonly string CHANNEL_ID = "xxxxxx";
const string NotificationHubConnectionString = "xxxxxx";
const string NotificationHubName = "xxxxxx";
protected override void OnCreate(Bundle bundle)
{
.
.
.
NotificationHub.SetListener(new AzureListener());
NotificationHub.Start(this.Application, NotificationHubName, NotificationHubConnectionString);
.
.
.
LoadApplication(new App());
}
}
public class AzureListener : Java.Lang.Object, INotificationListener
{
public void OnPushNotificationReceived(Context context, INotificationMessage message)
{
var intent = new Intent(context, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID);
notificationBuilder.SetContentTitle(message.Title)
.SetSmallIcon(Resource.Drawable.icon_category_announcement)
.SetContentText(message.Body)
.SetAutoCancel(true)
.SetShowWhen(false)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManager.FromContext(context);
notificationManager.Notify(0, notificationBuilder.Build());
}
}
I followed the following tutorial from Microsoft (1/12/2021):
[https://learn.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm#set-up-notification-hubs-in-your-project][1]
In the tutorial there seems to be an issue on steps 11 and 12 because they talk about a class name from the previous tutorial but then they use the new class name and some instructions seem to be missing:
Step 11. Add the following above your class declaration, and have your class inherit from Java.Lang.Object and implement the INotificationListener:
=> There is nothing above the class declaration
Step 12. Add the following code inside MyFirebaseMessagingService class, to process messages that are received.
=> The class name is actually AzureListener
What am I missing? How can I make the push notification to show up when the app is running and active?