Éder Rocha
Éder Rocha

Reputation: 1568

Plugin.FirebasePushNotification for xamarin doesn't work when app is closed

I'm not able to show push notifications using Plugin.FirebasePushNotification when my Xamarin app is closed.

This is what I have done so far:

MainActivity.cs

//some dependencies
using Plugin.FirebasePushNotification;
using System.Collections.Specialized;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace MasterDetailPageNavigation.Droid
{
    [Activity(Label = "app", Theme = "@style/MyTheme.Splash", MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        const string TAG = "MainActivity";

        internal static readonly string CHANNEL_ID = "my_notification_channel";
        internal static readonly int NOTIFICATION_ID = 100;

        protected override void OnCreate(Bundle bundle)
        {
            base.Window.RequestFeature(WindowFeatures.ActionBar);
            base.SetTheme(Resource.Style.MainTheme);
            base.OnCreate(bundle);
            Xamarin.Essentials.Platform.Init(this, bundle);
            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App(Param));

            FirebasePushNotificationManager.ProcessIntent(this, Intent);
            CrossFirebasePushNotification.Current.OnTokenRefresh += Current_OnTokenRefresh;
}

private void Current_OnTokenRefresh(object source, FirebasePushNotificationTokenEventArgs e)
{
    System.Diagnostics.Debug.WriteLine("NEW TOKEN => " + e.Token);
    App.TokenNotification = e.Token;
    Task.Run(() => SendRegistrationToServer(e.Token));
}

Application.cs

using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Plugin.FirebasePushNotification;
using static Android.Support.V4.App.NotificationCompat;

namespace MasterDetailPageNavigation.Droid
{
    [Application]
    public class MainApplication : Application
    {
        public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();

            //Set the default notification channel for your app when running Android Oreo
            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                //Change for your default notification channel id here
                FirebasePushNotificationManager.DefaultNotificationChannelId = "FirebaseDefaultChannel";

                //Change for your default notification channel name here
                FirebasePushNotificationManager.DefaultNotificationChannelName = "General";
                FirebasePushNotificationManager.DefaultNotificationChannelImportance = NotificationImportance.Max;
            }


            //If debug you should reset the token each time.
            #if DEBUG
                FirebasePushNotificationManager.Initialize(this,true);
            #else
                FirebasePushNotificationManager.Initialize(this, false);
            #endif

            //Handle notification when app is closed here
            CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
            {

                var intent = new Intent(this, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop);
                foreach (var key in p.Data.Keys)
                {
                    Console.WriteLine("String key: " + key + " = " + p.Data[key].ToString());
                    intent.PutExtra(key, p.Data[key].ToString());
                }
                
                p.Data.TryGetValue("title", out object Title);
                p.Data.TryGetValue("body", out object Body);

                var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.UpdateCurrent);
                var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                                      .SetSmallIcon(Resource.Drawable.ic_launcher_round)
                                      .SetContentTitle(Title.ToString())
                                      .SetContentText(Body.ToString())
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent)
                                      .SetPriority(PriorityHigh);
                                      //.SetStyle(new BigPictureStyle().SetSummaryText(Body.ToString()))

                var notificationManager = NotificationManagerCompat.From(this);
                notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
            };

           
        }
    }
}

AndroidManifest.xml (I'm wondering if this is yet necessary, I have commented out this for tests purposes and the behavior was the very same, but this is here for the old version of my application)

<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:enabled="true" 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>

Current behavior:

I can receive the messages when application is in foreground and background, but message isn't delivered when I close the app. If I comment out the code from method "CrossFirebasePushNotification.Current.OnNotificationReceived" everything stop work(I have read that it was necessary only for background mode but foreground seems to using it also). I'm almost doing a downgrade to make things works again.

Does anyone here see what I'm doing wrong here?

PS: I'm using firebase console to send test messages.

Upvotes: 2

Views: 3173

Answers (2)

user21019935
user21019935

Reputation: 1

Just in case this helps anyone else, I had the same issue of the Plugin.FirebasePushNotifications not working and for me it was that the Google Play Services were not functioning correctly in Xamarin.

I had to install the Google Play System Image under the Android SDKs & Tools screen as well as 'Google Play Services' under the Tools -> Extras section of the Android SDKs & Tools screen.

I then needed to follow this article in order to actually get my emulator to use Google Play services: https://www.codeproject.com/Articles/5266070/How-Can-I-Get-Google-Play-to-Work-on-Android-Emula

Upvotes: 0

&#201;der Rocha
&#201;der Rocha

Reputation: 1568

Just found the answer at project page of Plugin FireBasePushNotification:

3rd point of theirs FAQ:

"3 - You won't receive any push notifications if application is stopped while debugging, should reopen and close again for notifications to work when app closed. This is due to the application being on an unstable state when stopped while debugging."

So, everything what I have done to do was close and reopen application using only the phone(not debugging through visual studio), and bingo, now it works!

Upvotes: 2

Related Questions