有问题的人,
我想加载一个显示推送通知字符串内容的页面,但是触发OnReceivedMessage()的次数越来越多,这等于我进入DisplayPage并返回的次数。
因此,我第一次运行时,OnRevceivedMessage触发器会打开我关闭的DisplayPage()并通过PopAsync()返回上一页。我第二次使用Postman发送通知,并执行一个循环来加载DisplayNotificationPage,然后返回,OnReceivedMessage()触发两次,然后每次运行触发3次,等等。
这是怎么回事?我认为它与订阅有关。.我该如何解决?
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NotificationReceivingPage : ContentPage
{
public NotificationReceivingPage ()
{
InitializeComponent ();
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Subscribe<object, string>(this, App.NotificationReceivedKey, OnMessageReceived);
}
private void OnMessageReceived(object sender, string incomingNotificationBody) // gets triggered x1, x2, x3... and so on
{
if (!string.IsNullOrEmpty(incomingNotificationBody))
{
Navigation.PushAsync(new NotificationDisplayPage(incomingNotificationBody));
}
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<object>(this, App.NotificationReceivedKey);
}
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NotificationDisplayPage : ContentPage
{
ISimpleAudioPlayer soundPlayer;
private static string incomingMessage = null;
//default constructor
public AlarmDisplayPage ()
{
InitializeComponent ();
}
// overloaded constructor that receives incoming notification body
public AlarmDisplayPage(string messageBody)
{
InitializeComponent();
if (messageBody != null)
{
incomingMessage = messageBody;
}
//alarm to sound on incoming message
var assembly = typeof(AlarmDisplayPage);
alertHeader.Source = ImageSource.FromResource("ShakeAlarmRR1.Assets.Images.test-event-header.png", assembly);
}
protected override void OnAppearing()
{
base.OnAppearing();
stopAlarmButton.IsEnabled = true;
//initialize soundplayer
soundPlayer = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
soundPlayer.Load(GetStreamFromFile("alarm.mp3"));
if (!string.IsNullOrEmpty(incomingMessage))
{
setEventDetails();
//play the alarm
soundPlayer.Play();
}
}
protected override void OnDisappearing()
{
base.OnDisappearing();
soundPlayer.Stop();
incomingMessage = null;
}
private Stream GetStreamFromFile(string mediaFilename)
{
var assembly = typeof(App).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream("ShakeAlarmRR1.Assets.Sounds." + mediaFilename);
return stream;
}
private void stopAlarmButton_Clicked(object sender, EventArgs e)
{
stopAlarmButton.IsEnabled = false;
Navigation.PopToRootAsync();
}
private void setEventDetails()
{
if (!string.IsNullOrEmpty(incomingMessage))
{
labelEventType.Text = incomingMessage;
}
else
{
labelEventType.Text = "No Data";
}
}
}