user14187680
user14187680

Reputation:

How to implement Timer Elapsed Event on UserInterface thread in Xamarin Android

Am implementing a System Timer on Xamarin Android and i have a problem with the elapsed event not raising a dialog box with the message "Time is up" when the countdown is Over... I figured the problem might be not implementing the event on the User Interface thread so i need your help accomplishing that... Here is my code for the Timer

    class SecondActivity : AppCompatActivity
    {
        int counter = 10;
        private System.Timers.Timer _timer;
        private int _countSeconds;
        protected override void OnCreate(Bundle savedInstanceState)
        {
    _timer = new System.Timers.Timer();
            //Trigger event every second
            _timer.Interval = 1000;
            _timer.Elapsed += OnTimedEvent;
            //count down 5 seconds
           

            _timer.Enabled = true;
            _countSeconds = 5;
  }
        private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            _countSeconds--;
            if (_countSeconds == 0) {
                _timer.Stop();
            Switch switch1 = this.FindViewById<Switch>(Resource.Id.switch2);
                Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog alert = dialog.Create();
                alert.SetTitle("");
                alert.SetMessage("Simple Alert");
                alert.SetButton("OK", (c, ev) =>
                {
                    // Ok button click task  
                });
                switch1.Checked = false;
        }

I just want the Elapsed event handler to display an alert dialog box when the variable count down equals zero, Thank You

Upvotes: 1

Views: 838

Answers (1)

user14187680
user14187680

Reputation:

After the first comment pointed me to a related question i found the method to implement the user thread and it now works as intended to display the alert dialog...

 private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
//This is how to make the Timer callback on the UI
            RunOnUiThread(() =>
            {
            _countSeconds--;
                if (_countSeconds == 0)
                {
                    Switch switch1 = this.FindViewById<Switch>(Resource.Id.switch2);
                    Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
                    Android.App.AlertDialog alert = dialog.Create();
                    alert.SetTitle("Its over");
                    alert.SetMessage("Simple Alert");
                    alert.SetButton("OK", (c, ev) =>
                    {
                    // Ok button click task  
                });
                    alert.Show();
                    switch1.Checked = true;
                }
            });
        }

Upvotes: 1

Related Questions