我正在制作一个计时器应用程序,所以后台非常重要。我这样做的方式是通过此链接中概述的这种方法。 https://robgibbens.com/backgrounding-with-xamarin-forms/基本上是一个 Ticked 消息循环和更新视图。
问题是我想同时运行多个计时器。这使我的程序感到困惑,并且计时器开始接收彼此的消息。知道如何在一个类与 AppDelegate.cs 和 MainActivity.cs 类之间的消息中心私下发送消息吗?
谢谢
我正在制作一个计时器应用程序,所以后台非常重要。我这样做的方式是通过此链接中概述的这种方法。 https://robgibbens.com/backgrounding-with-xamarin-forms/基本上是一个 Ticked 消息循环和更新视图。
问题是我想同时运行多个计时器。这使我的程序感到困惑,并且计时器开始接收彼此的消息。知道如何在一个类与 AppDelegate.cs 和 MainActivity.cs 类之间的消息中心私下发送消息吗?
谢谢
您可以为 设置不同的消息名称MessagingCenter
,如以下代码。一条消息调用OneMessage
,另一条消息调用TwoMessage
,
private void TimerUp(object sender, ElapsedEventArgs e)
{
currentCount += 1;
MessagingCenter.Send<App, string>(App.Current as App, "OneMessage", currentCount.ToString());
currentCount2 += 2;
MessagingCenter.Send<App, string>(App.Current as App, "TwoMessage", currentCount2.ToString());
}
当我们接收到 MessagingCenter 时,我们可以使用 MessageName 来区分它们
MessagingCenter.Subscribe<App, string>(App.Current, "OneMessage", (snd, arg) =>
{
Device.BeginInvokeOnMainThread(() => {
//we can get the information by arg
myLabel.Text = arg;
});
});
MessagingCenter.Subscribe<App, string>(App.Current, "TwoMessage", (snd, arg) =>
{
Device.BeginInvokeOnMainThread(() => {
//we can get the information by arg
myLabel2.Text = arg;
});
});
这是运行的gif。
这是我的演示。
https://github.com/851265601/MessageCenterDemo
我注意到您想让后台服务始终运行。由于 Android 8.0 限制。如果应用程序在后台,正常服务将被终止。所以我建议你使用前台服务来保持服务始终运行。
https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services
这是我关于前台服务的演示。