如何在Xamarin Android中的UserInterface线程上实现计时器经过的事件

问题描述

Am在Xamarin Android上实现了系统计时器,当倒计时结束时,我遇到了一个已发生事件,即未引发带有消息“ Time up up”的对话框的问题... 我认为问题可能不是在用户界面线程上实现的,所以我需要您的帮助来实现这一目标... 这是我的计时器代码

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

我只希望Elapsed事件处理程序在变量倒计数等于0时显示一个警告对话框,谢谢

解决方法

在第一条评论向我提出一个相关问题之后,我找到了实现用户线程的方法,现在它可以按预期的方式显示警报对话框...

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