插件.FirebasePushNotification for xamarin在应用程序关闭时不工作

ztyzrc3y  于 2023-01-18  发布在  其他
关注(0)|答案(2)|浏览(130)

当我的Xamarin应用程序关闭时,我无法使用Plugin.FirebasePushNotification显示推送通知。
这是我迄今为止所做的:

  • 添加了google-services.json并将其构建操作设置为GoogleServiceJson

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(我想知道这是否是必要的,出于测试目的,我已经注解掉了它,行为是非常相同的,但这是针对我的应用程序的旧版本)

<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>

当前行为:
当应用程序在前台和后台时,我可以接收消息,但当我关闭应用程序时,消息不会传递。如果我注解掉方法“CrossFirebasePushNotification.Current.OnNotificationReceived”中的代码,一切都停止工作(我读到过,这只对后台模式是必要的,但前台似乎也使用它)。
有人知道我做错了什么吗?
PS:我正在使用firebase控制台发送测试消息。

f4t66c6m

f4t66c6m1#

刚刚在插件FireBasePushNotification的项目页面找到了答案:
theirs FAQ的第3个点:
3 -如果应用程序在调试期间停止,则不会收到任何推送通知,应重新打开并再次关闭,以便在应用程序关闭时通知生效。这是由于应用程序在调试期间停止时处于不稳定状态。
所以,我所做的一切就是只使用手机关闭和重新打开应用程序(而不是通过visual studio调试),宾果,现在它工作了!

0lvr5msh

0lvr5msh2#

以防万一这对其他人有帮助,我也遇到了同样的问题,插件FireBasePushNotifications不起作用,对我来说,这是Google Play服务在Xamarin中不能正常运行。
我必须在Android SDK &工具屏幕下安装Google Play系统映像,以及在Android SDK &工具屏幕的工具-〉附加部分下安装“Google Play服务”。
然后,我需要按照这篇文章,以实际获得我的模拟器使用Google Play服务:https://www.codeproject.com/Articles/5266070/How-Can-I-Get-Google-Play-to-Work-on-Android-Emula

相关问题