如何解决Xamarin消息中心多个相同消息的不同结果
我正在制作计时器应用程序,因此背景非常重要。我这样做的方法是通过此链接中概述的这种方法。 https://robgibbens.com/backgrounding-with-xamarin-forms/基本上是滴答邮件循环并更新视图。
问题是我想一次运行多个计时器。这使我的程序感到困惑,并且计时器开始接收对方的消息。知道如何在一个类与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,"TwoMessage",currentCount2.ToString());
}
当我们接收MessagingCenter时,可以使用MessageName来区分它们
MessagingCenter.Subscribe<App,string>(App.Current,(snd,arg) =>
{
Device.BeginInvokeOnMainThread(() => {
//we can get the information by arg
myLabel.Text = arg;
});
});
MessagingCenter.Subscribe<App,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。如果后台运行应用程序,将无法正常服务。因此,我建议您使用Foreground服务来保持该服务始终运行。
https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services
这是我有关前台服务的演示。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。