我正在努力整合Firebase 推送通知到我的应用程序。
请找到我的火力基地Firebase消息服务 class.
如果应用程序打开并运行,则一切正常。但是,如果应用程序未打开/如果我切换到其他应用程序(我的应用程序未关闭)。我收到通知,但当我点击通知时,它会重新启动应用程序而不恢复。
我正在使用启动模式LaunchMode = LaunchMode.SingleTop在我的主要活动中。
如果应用程序打开,我会收到响应新意图覆盖主要活动的方法。
谁能帮我找出真正的原因。请帮忙。
[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
}