问题
So I'm new to XF and I'm wondering about AppState/Activity life cycle on Android.
The code directly below this is in a file called test.xaml.cs.
How the sound works is you can say something like startSound.Play() or startSound.Stop() to start or stop sound in the app. I have noticed a bug that doesn't stop sound when the rest of the app resets via the back button (even though it's held in memory?)
public Test()
{
startSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
startSound.Load(Path.Combine($"Audio", "startBeep.wav"));
stopSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
stopSound.Load(Path.Combine($"Audio", "stopBeep.wav"));
winSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
winSound.Load(Path.Combine($"Audio", "winBeep.wav"));
endSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
endSound.Load(Path.Combine($"Audio", "endBeep.wav"));
addSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
addSound.Load(Path.Combine($"Audio", "addBeep.wav"));
}
What I would like to do is in the app.xaml.cs file to go into protected override void OnSleep() and write startSound.stop(); so that the sound stops whenever the app sleeps. However I do not know how to access the public function of Test in test.xaml.cs.
This is the code line for app.xaml.cs
protected override void OnSleep()
{
Debug.WriteLine("OnSleep");
// Handle when your app sleeps
}
I've used the debug to make sure that the app state changes so I know the OnSleep() works properly.
回答1:
You can use MessagingCenter to accomplish that.
Xamarin.Forms MessagingCenter enables view models and other components to communicate with without having to know anything about each other besides a simple Message contract.
Just send a message in the OnSleep of your App and subscribe to the message on your Test:
In your OnSleep:
MessagingCenter.Send<App>(this, "OnSleep");
In your Test:
MessagingCenter.Subscribe<App>(this, "OnSleep", (sender) => {
startSound.stop();
});
HIH
来源:https://stackoverflow.com/questions/53522477/xamarin-forms-how-do-i-access-a-public-function-from-another-cs-file