mistrypragnesh40 / PushNotificationDemoMAUI

33 stars 10 forks source link

FirebaseService OnNewToken #5

Open jitendrajadav opened 1 year ago

jitendrajadav commented 1 year ago

I have MAUI application downloaded and OnNewToken is not calling so I am not able to get token could you please check this I think we have call firebaseService and start somewhere

masterofdaemon commented 1 year ago

hello, can i use instead of Firebase Admin, lib from this sample https://github.com/SyedMohsinAliZaidi/.NetMauiEmailAuthFirebase , login by email/pass does it work with cloud messaging?

jeff-eats-pubsubs commented 1 year ago

@jitendrajadav I am having the same issue. Have you had any success here?

jeff-eats-pubsubs commented 1 year ago

@jitendrajadav Try adding [Activity] to your firebase service. That seemed to work in my case.

    [Activity]
    [Service(Exported = true)]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]

Also make sure if you are using an emulator that you have Google APIs enabled

jitendrajadav commented 1 year ago

Hi @jeff-eats-pubsubs , I have tried with [Activity] adding on firebase services still not working.

masterofdaemon commented 1 year ago

same, don't works for me : Google.Apis.Auth.OAuth2.Responses.TokenResponseException: 'Error:"invalid_grant", Description:"Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values in the JWT claim.", Uri:""'

PWH1987 commented 7 months ago

hi, anyone have any luck about the token ?

its-jefe commented 7 months ago

Here's what I've got in my FirebaseService.cs

MyCoolApp\Platforms\Android\Services\FirebaseService.cs

using Android.App;
using Android.Content;
using AndroidX.Core.App;

namespace MyCoolApp.Platforms.Android.Services
{
    [Activity]
    [Service(Exported = false)]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class FirebaseService : FirebaseMessagingService
    {
        public FirebaseService()
        {
        }

        public override void OnNewToken(string token)
        {
            base.OnNewToken(token);
        }

        public override void OnMessageReceived(RemoteMessage message)
        {
            base.OnMessageReceived(message);
            var notification = message.GetNotification();
        }

        private void SendNotification(string messageBody, string title, IDictionary<string, string> data)
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            intent.AddFlags(ActivityFlags.SingleTop);

            foreach (var key in data.Keys)
            {
                string value = data[key];
                intent.PutExtra(key, value);
            }

            // switch statement for some kind of message type id in the data param
            var pendingIntent = PendingIntent.GetActivity(this,
                MainActivity.NotificationID, intent, PendingIntentFlags.OneShot | PendingIntentFlags.Immutable);

            var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.Channel_ID)
                .SetContentTitle(title)
                .SetContentText(messageBody)
                .SetChannelId(MainActivity.Channel_ID)
                .SetContentIntent(pendingIntent)
                .SetAutoCancel(true)
                .SetPriority((int)NotificationPriority.Max);

            var notificationManager = NotificationManagerCompat.From(this);
            notificationManager.Notify(MainActivity.NotificationID, notificationBuilder.Build());
        }
    }
}
its-jefe commented 7 months ago

MyCoolApp\Platforms\Android\MainActivity.cs

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AndroidX.Activity;
using AndroidX.Core.App;
using AndroidX.Core.Content;

namespace MyCoolApp;

[Activity(
    Theme = "@style/Maui.SplashTheme",
    //Theme = "@style/Maui.MainTheme.NoActionBar",
    MainLauncher = true,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density
)]
public class MainActivity : MauiAppCompatActivity
{
    internal static readonly string Channel_ID = "NotificationChannel";
    internal static readonly int NotificationID = 101;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        if (ContextCompat.CheckSelfPermission(this, Android.Manifest.Permission.PostNotifications) == Permission.Denied)
        {
            ActivityCompat.RequestPermissions(this, new String[] { Android.Manifest.Permission.PostNotifications }, 1);
        }

        CreateNotificationChannel();

        OnBackPressedDispatcher.AddCallback(this, new BackPress(this));
    }

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

        if (intent.Extras != null)
        {
            foreach (var key in intent.Extras.KeySet())
            {
                if (key == "NavigationID")
                {
                    string idValue = intent.Extras.GetString(key);
                    if (Preferences.ContainsKey("NavigationID"))
                        Preferences.Remove("NavigationID");

                    Preferences.Set("NavigationID", idValue);

                    WeakReferenceMessenger.Default.Send(new PushNotificationReceived(true));
                }
            }
        }
    }

    private void CreateNotificationChannel()
    {
        if (OperatingSystem.IsOSPlatformVersionAtLeast("android", 26))
        {
            var channel = new NotificationChannel(Channel_ID, "Notification Channel", NotificationImportance.Max);

            var notificaitonManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);
            notificaitonManager.CreateNotificationChannel(channel);
        }
    }

    class BackPress : OnBackPressedCallback
    {
        private readonly Activity activity;
        private long backPressed;

        public BackPress(Activity activity) : base(true)
        {
            this.activity = activity;
        }

        public override void HandleOnBackPressed()
        {
            AppSharedState SharedState = ServiceHelper.GetService<AppSharedState>();
            var Back = SharedState.BackButtonPressed;
            if (Back is not null)
            {
                Back.Invoke();
            }

            var navigation = Microsoft.Maui.Controls.Application.Current?.MainPage?.Navigation;
            if (navigation is not null && navigation.NavigationStack.Count <= 1 && navigation.ModalStack.Count <= 0)
            {
                const int delay = 2000;
                if (backPressed + delay > DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
                {
                    activity.FinishAndRemoveTask();
                    Process.KillProcess(Process.MyPid());
                }
                else
                {
                    Android.Widget.Toast.MakeText(activity, "Close", ToastLength.Long)?.Show();
                    backPressed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                }
            }
        }
    }
    public override bool DispatchTouchEvent(MotionEvent e)
    {
        return base.DispatchTouchEvent(e);
    }
    public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
    {
        return base.OnKeyDown(keyCode, e);
    }
    public override void TakeKeyEvents(bool get)
    {
        base.TakeKeyEvents(get);
    }
    public override void OnBackPressed()
    {
        //base.OnBackPressed();
    }
}
its-jefe commented 7 months ago

Hope this helps