[英]Xamarin Message Center Multiple Of The Same Message Different Results
我正在制作一個計時器應用程序,因此背景非常重要。 我這樣做的方式是通過此鏈接中概述的方法。 https://robgibbens.com/backgrounding-with-xamarin.forms/基本上是 Ticked 消息和更新視圖的循環。
問題是我想同時運行多個計時器。 這讓我的程序感到困惑,計時器開始接收彼此的消息。 知道如何在一個 class 與 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://learn.microsoft.com/en-us/xamarin.android/app-fundamentals/services/foreground-services
這是我關於前台服務的演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.