Xamarin Forms-Android-FCM-当应用程序处于前台,后台且滑动关闭状态时,会收到抬头通知 [英] Xamarin Forms - Android - FCM - Heads up notification when app is in foreground, background and swiped closed

查看:58
本文介绍了Xamarin Forms-Android-FCM-当应用程序处于前台,后台且滑动关闭状态时,会收到抬头通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请给我一些有关Android推送通知的帮助.对于上下文,我已经阅读了数十篇有关如何实现android推送通知的堆栈溢出文章.我见过的所有帖子仅涵盖了部分问题.当应用程序处于前台或后台时,我已经能够成功接收推送通知并显示提示通知,但是当应用程序在关闭状态下滑动时,它不起作用.为了在关闭应用程序时将通知显示在状态栏上,您需要使用通知"负载中的对象而不是数据"对象.对象.

I need some help with android push notifications, please. For context, I've read dozens of stack overflow posts on how to implement push notifications for android. All of the posts I've seen only cover part of the problem. I've been able to successfully receive push notifications and display a heads up notification when the app is in the foreground or background, but then it doesn't work when the app is swiped closed. In order for the notification to display on the status bar when the app is swiped closed, you need to use a "notification" object in the payload instead of a "data" object.

我想要实现的是-当应用程序处于以下任意一种状态(前景,背景和滑动关闭)时,我需要状态栏通知,声音和提示通知.

What I am trying to achieve is this - I need a status bar notification, a sound and a heads up notification when the app is in any of these states - foreground, background and swiped closed.

要实现此目的,代码,有效负载json和清单配置的秘诀是什么?我在手机上使用的任何主要应用程序-eBay,etsy,amazon和我下载的大多数应用程序都可以完成所有这些操作,因此无论fcm指南中的内容如何,​​它都必须是可能的.

What is the secret recipe of code, payload json, and manifest config to make this happen? Any major app that I have on my phone - eBay, etsy, amazon and most apps that I download can do all of this, so it must be possible regardless of what some off the fcm guides say.

这是我们的FireBaseMessagingService中的onMessageReceived方法:

Here is our onMessageReceived method in our FireBaseMessagingService:

  public override void OnMessageReceived(RemoteMessage message)
  {
    try
    {
        base.OnMessageReceived(message);
        string messageBody = string.Empty;
        string messageTitle = string.Empty;

        if (message.GetNotification() != null)
        {
            messageTitle = message.GetNotification().Title;
            messageBody = message.GetNotification().Body;
        }
        else
        {
            if (message.Data.Values.Count == 1)
            {
                messageTitle = "Alerts Occurred";
                messageBody = message.Data.Values.First();
            }
            else if (message.Data.Values.Count == 2)
            {
                messageTitle = message.Data.Values.ToList()[0];
                messageBody = message.Data.Values.ToList()[1];
            }
        }

        SendLocalNotification(messageTitle, messageBody);

    }
    catch (Exception e)
    {
        NotificationHubHelper.LogInfo($"Error receiving message on device: {e.Message}");
    }
  }

   private void SendLocalNotification(string title, string body)
  {
    try
    {
        _notificationBadgeCount++;
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        intent.PutExtra("message", body);
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

        int notificationIconId = 
Resources.GetIdentifier(NotificationHubHelper.AndroidNotificationIconImage, "drawable", 
AppInfo.PackageName);
        NotificationHubHelper.LogInfo($"Found notification icon with id: {notificationIconId}");
        var notificationBuilder = new NotificationCompat.Builder(this, 
NotificationHubHelper.NotificationChannelName)
            .SetContentTitle(title)
            .SetSmallIcon(notificationIconId) //.SetSmallIcon(ApplicationInfo.Icon)
            .SetContentText(body)
            .SetAutoCancel(true)
            .SetShowWhen(false)
            .SetContentIntent(pendingIntent)
            .SetPriority((int)NotificationPriority.Max);

        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            notificationBuilder.SetChannelId(NotificationHubHelper.NotificationChannelName);
        }

        var notificationManager = NotificationManager.FromContext(this);
        notificationManager.Notify(0, notificationBuilder.Build());
        CrossBadge.Current.SetBadge(_notificationBadgeCount);
    }
    catch (Exception e)
    {
        NotificationHubHelper.LogInfo($"Error sending local notification on device: {e.Message}");
    }
 }

这是我们的清单:

 <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" 
    android:versionName="1.0.9" package="HIDDEN_FROM_POST" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="29" />
    <application android:allowBackup="false" android:label="HIDDEN_FROM_POST" 
    android:icon="@drawable/HIDDEN_FROM_POST">
        <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="HIDDEN_FROM_POST" />
        <meta-data android:name="com.google.android.gms.version" 
    android:value="@integer/google_play_services_version" />
        <uses-library android:name="org.apache.http.legacy" android:required="false" />
        <provider android:name="android.support.v4.content.FileProvider" 
    android:authorities="${applicationId}.fileprovider" android:exported="false" 
    android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" 
    android:resource="@xml/file_paths"></meta-data>
        </provider>
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" 
    android:exported="false" />
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" 
    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>
    <meta-data
      android:name="com.google.firebase.messaging.default_notification_icon"
      android:resource="@drawable/HIDDEN_FROM_POST" />
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
  <uses-permission android:name="com.anddoes.launcher.permission.UPDATE_COUNT"/>
  <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
  <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS"/>
  <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
  <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
  <uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" />
  <uses-permission android:name="com.htc.launcher.permission.UPDATE_SHORTCUT" /> 
  <uses-permission android:name="com.sec.android.provider.badge.permission.READ" />
  <uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" />
  <uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />
  <uses-permission android:name="com.sonymobile.home.permission.PROVIDER_INSERT_BADGE" />
</manifest>

最后,这是我们尝试过的最新有效负载:

And, finally, here is the latest payload we've tried:

   {
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    },
    "data":{
        "message":"this is a message",
        "title":"title"
    }
}

通过上述操作,我们将在滑动关闭应用程序时收到状态栏通知,在应用程序处于后台时会显示状态栏通知,而在应用程序处于前台时会显示带有抬头通知的状态栏通知.

With the above, we get a status bar notification when the app is swiped closed, a status bar notification when the app is in background and a status bar notification with heads up notification when the app is in the foreground.

我们如何在所有情况下获得抬头通知?

How do we get the heads up notification in all scenarios?

Len

推荐答案

这可能是一个长镜头,但经过大量挖掘,我发现在后台,尤其是在被刷掉时,您无权访问XamarinForms对象因为只有在您实际完成start活动后,该实例才会被实例化.

This could be a long shot but after a lot of digging I found that when in background and especically when swiped away you don't have access to the XamarinForms object as it's only instantiated once you actually go through the start activity.

例如如果这实际上是使用DependencyService或另一个Forms库,则将收到错误.

E.g. if this is actually using a DependencyService or another Forms library you will get an error.

CrossBadge.Current.SetBadge(_notificationBadgeCount)

还要确保从通知服务器将默认优先级设置为 high ,这是默认设置,这是正常的,如果将其清除,不会导致应用程序唤醒.

also make sure from your notification server you are setting the priority to high it is normal by default which will not cause the WAKEUP of the app if swiped away.

priority: "high",

android: {
    priority: "high",
    notification: {
        title: title,
        body: body,
        sound: "default",
        priority: "high",
        sticky: false,
        defaultSound: true,
        defaultVibrateTimings: true,
    },
    data: {        
       title: title,
       body: body
   }
}

这篇关于Xamarin Forms-Android-FCM-当应用程序处于前台,后台且滑动关闭状态时,会收到抬头通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆