Xamarin Message Center Multiple Of The Same Message Different Results

434 views Asked by At

I'm making a timer app, so backgrounding is super important. The way I am doing it is through this method outlined in this link. https://robgibbens.com/backgrounding-with-xamarin-forms/ Basically a loop of Ticked messages and updating the view.

The issue is I want to have multiple timers running at once. This confuses my program and the timers start receiving eachothers' messages. Any idea how you can send messages privately in the message center between one class and the AppDelegate.cs and MainActivity.cs classes?

Thanks

1

There are 1 answers

2
Leon On BEST ANSWER

You can set different message names for MessagingCenter, like following code. One Message called OneMessage, the other message called 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());
        }

When we recevice the MessagingCenter, we can use MessageName to distinguish them

  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;
                });
            });
            

Here is running gif.

enter image description here

Here is my demo.

https://github.com/851265601/MessageCenterDemo

I notice you want to make the background service always running. Due to Android 8.0 limiation. Normal service will be killed if Application in the background. So I advice you to use Foreground service to keep the service always running.

https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services

Here is my demo about foreground service.

https://github.com/851265601/ForeGroundService