首页 > 解决方案 > 如何在 Xamarin Android 中的 UserInterface 线程上实现 Timer Elapsed Event

问题描述

我在 Xamarin Android 上实现了一个系统计时器,当倒计时结束时,我遇到了一个问题,即经过的事件没有引发带有消息“时间到了”的对话框......我认为问题可能是没有在用户界面线程,所以我需要你的帮助来完成...这是我的计时器代码

    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 事件处理程序在变量倒计时等于零时显示一个警报对话框,谢谢

标签: c#androidxamarintimeralert

解决方案


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

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

推荐阅读