应用程序运行时处理推送通知

时间:2018-03-19 15:31:38

标签: android xamarin.android

我正在使用Google通知(FCM),我注意到如果应用程序位于后台,则以下代码仅 。 如果我在应用程序运行时收到推送通知,则不会发生任何事情。

即使应用正在运行,也可以使用NotificationManager显示通知吗?

[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
    public override void OnMessageReceived(RemoteMessage message)
    {
        if (message.Data != null)
        {
            ShowNotification(message.Data.ToDictionary(t => t.Key, t => t.Value));
        }
    }

    void ShowNotification(IDictionary<string, string> data)
    {
        var manager = (NotificationManager) GetSystemService(NotificationService);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "M_CH_ID");

        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

        builder.SetSmallIcon(Resource.Mipmap.Icon)
               .SetContentTitle(GetString(Resource.String.appName))
               .SetContentText("TOOOOOODO") //TODO
               .SetContentIntent(pendingIntent)
               .SetWhen(10)
               .SetAutoCancel(true);

       manager.Notify(0, builder.Build());
    }
}

1 个答案:

答案 0 :(得分:0)

问题仅发生在Android Oreo上。 这是正确的代码:

var manager = (NotificationManager)ctx.GetSystemService(Context.NotificationService);

        if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            var notificationChannel = new NotificationChannel("AAA", "My Notifications", NotificationImportance.Default);

            // Configure the notification channel.
            notificationChannel.Description = "Channel description";
            notificationChannel.EnableLights(true);
            notificationChannel.SetVibrationPattern(new long[] { 0, 1000, 500, 1000 });
            notificationChannel.EnableVibration(true);
            manager.CreateNotificationChannel(notificationChannel);
        }


        var builder = new NotificationCompat.Builder(ctx, "AAA");

        var intent = new Intent(ctx, typeof(LoginActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent);

        builder.SetSmallIcon(Resource.Mipmap.Icon)
               .SetContentTitle(title)
               .SetContentText(body)
               .SetContentIntent(pendingIntent)
               .SetAutoCancel(true);

        manager.Notify(0, builder.Build());