Guys im having an issue,
I want to load a page that displays the push notification string content but the OnReceivedMessage() gets triggered an increasing number of times equal to the amount of times I go to the DisplayNotificationPage and back.
So first time I run, the OnRevceivedMessage triggers, opens the DisplayNotificationPage() that i close and return to the previous page through PopAsync(). The second time the OnReceivedMessage() triggers twice, then 3 times etc for every run.
What is going on? I think it has to do something with subscribing.. how can i fix this?
[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("SApp.Assets.Images.mypic-header.png", assembly);
}
protected override void OnAppearing()
{
base.OnAppearing();
stopAlarmButton.IsEnabled = true;
//initialize soundplayer
soundPlayer = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
soundPlayer.Load(GetStreamFromFile("mysound.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("SApp.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";
}
}
}