我正在做一个计时器应用,所以背景知识是非常重要的。我这样做的方式是通过这个链接中概述的方法。https://robgibbens.com/backgrounding-with-xamarin-forms/基本上是一个计时消息和更新视图的循环。
问题是我想同时运行多个计时器。这混淆了我的程序,计时器开始接收eachothers的消息。您知道如何在一个类与AppDelegate.cs和MainActivity.cs类之间的消息中心私下发送消息吗?
谢谢
发布于 2020-08-20 14:44:24
您可以为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
我注意到您想让后台服务始终运行。Due to Android 8.0 limiation。如果应用程序在后台,正常的服务将被终止。因此,我建议您使用前台服务来保持服务始终运行。
https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services
这是我关于前台服务的演示。
https://stackoverflow.com/questions/63497455
复制相似问题