【发布时间】:2020-05-22 17:09:51
【问题描述】:
我正在努力将 firebase 推送通知集成到我的应用程序中。
请找到我的 firebase FirebaseMessagingService 类。
如果应用程序已打开并运行,一切正常。但是,如果应用程序未打开/如果我切换到其他应用程序(我的应用程序未关闭)。我收到通知,但是当我点击通知时,它会重新启动应用程序而不恢复。
我在我的主要活动中使用启动模式 LaunchMode = LaunchMode.SingleTop。
如果应用程序打开,我会在主活动的 OnNewIntent 覆盖方法中得到响应。
谁能帮我找出真正的原因。请帮忙。
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class DriverAppMessagingService : FirebaseMessagingService
{
#region Overriden Methods
public override void OnMessageReceived(RemoteMessage message)
{
base.OnMessageReceived(message);
var parameters = new Dictionary<string, object>();
var notification = message.GetNotification();
if (null != notification)
{
if (!string.IsNullOrEmpty(notification.Body))
{
parameters.Add("Body", notification.Body);
}
if (!string.IsNullOrEmpty(notification.BodyLocalizationKey))
{
parameters.Add("BodyLocalizationKey", notification.BodyLocalizationKey);
}
// convert the incoming message to a local notification
SendLocalNotification(parameters);
// send the incoming message directly to the MainActivty
SendNotificationToMainActivity(parameters);
}
}
public override void OnNewToken(string p0)
{
base.OnNewToken(p0);
//Persist the token to app settings for registration purpose.
AppDefinition.Helpers.Settings.Current.PnsHandle = p0;
}
#endregion
#region Private Methods
/// <summary>
///
/// </summary>
/// <param name="args"></param>
private void SendNotificationToMainActivity(Dictionary<string, object> args)
{
if (CrossCurrentActivity.Current.Activity is MainActivity activity)
{
var message = args["Body"].ToString();
activity.TriggerPushNotification(message);
}
}
/// <summary>
/// Method to trigger the local notification.
/// </summary>
/// <param name="args"></param>
private void SendLocalNotification(Dictionary<string, object> args)
{
//TODO Only using one token from message response.
var message = args["Body"].ToString();
var intent = new Intent(CrossCurrentActivity.Current.Activity, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
intent.PutExtra("message", message);
var pendingIntent = PendingIntent.GetActivity(CrossCurrentActivity.Current.Activity, 0, intent, PendingIntentFlags.UpdateCurrent | PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(CrossCurrentActivity.Current.Activity, Constants.NotificationChannelName)
.SetContentTitle(Constants.ContentTitle)
.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
.SetContentText(message)
.SetAutoCancel(true)
.SetShowWhen(false)
.SetLights(0xff0000, 100, 100)
.SetContentIntent(pendingIntent);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
notificationBuilder.SetChannelId(Constants.NotificationChannelName);
}
var notificationManager = NotificationManager.FromContext(CrossCurrentActivity.Current.Activity);
notificationManager.Notify(0, notificationBuilder.Build());
}
#endregion
}
【问题讨论】:
标签: xamarin.forms xamarin.android firebase-notifications