So I have an app that on a button press: starts a timer, cycles through one (++) piece of data and hides the start button and instead shows a stop and next button. I have looked into messaging center and I thought it was fixing the problem (here's the link Xamarin.Forms how do I access a public function from another CS file?) but it didn't fix the problem completely.
If the app has the timer running (aka you hit the start button) and then interrupt the process by hitting the home button on your phone, the app works fine and the app hides the stop/next buttons and shows the start button and stops the timer. If you haven't started the process at all (aka you haven't hit the start button) and you hit the home button on your phone the app throws an exception error because what I'm changing with messaging center "doesn't need changing because it never changed". Is there a better way to handle this situation?
Can I use if/else statements in app state with messagingcenter?? I'm stuck.
App.xaml.cs
protected override void OnSleep()
{
// Handle when your app sleeps
Debug.WriteLine("~~~~~~~~~~~~~~OnSleep~~~~~~~~~~~~~");
MessagingCenter.Send<App>(this, "OnSleep");
}
MainPage.xaml.cs
MessagingCenter.Subscribe<App>(this, "OnSleep", (sender) => {
//shows start button instead of stop button
StartGrid.IsVisible = true;
//hides stop button
StopNextGrid.IsVisible = false;
//stops timer
timer.Stop();
timer = null;
//stops sound
startSound.Stop();
stopSound.Play();
});
Just can see the partial code,you should check if your timer is initialized before executing the method.
When you do not click the start button, you need to check whether the timer
is initialized, in order to perform the following timer operation.
If no want to know whether timer is initialized. You can try this:
Modify in your notification handling method.If the state of your timer and button has not changed, you don't need to do anything in the notification.Here I use the timer
as a judgment.
MessagingCenter.Subscribe<App>(this, "OnSleep", (sender) => {
//shows start button instead of stop button
if (null != timer)
{
StartGrid.IsVisible = true;
//hides stop button
StopNextGrid.IsVisible = false;
//stops timer
timer.Stop();
timer = null;
//stops sound
startSound.Stop();
stopSound.Play();
}
});