Xamarin.Android 使用Timer 并更改UI

时间:2023-03-09 15:52:32
Xamarin.Android 使用Timer 并更改UI

http://blog.****.net/ozhangsan12345/article/details/72653070

第一步:创建timer对象

  1. //创建timer对象
  2. Timer _dispatcherTimer;
  3. //计数
  4. int sec = 60;

第二步: 实例化timer并给委托事件

  1. TimerCallback timerDelegate = new TimerCallback(Tick); //tick为执行防范
  2. _dispatcherTimer = new Timer(timerDelegate, null, 0, 1000);

//执行方法

  1. public void Tick(object state)
  2. {
  3. this.RunOnUiThread(() =>
  4. {
  5. if (sec > 0)
  6. {
  7. smsbt.Text = sec.ToString() + "秒可重发";
  8. sec--;
  9. }
  10. else
  11. {
  12. _dispatcherTimer.Dispose();
  13. sec = 60;
  14. smsbt.Text = "获取验证码";
  15. }
  16. });
  17. }

//使用

    1. {
    2. TimerCallback timerDelegate = new TimerCallback(Tick);
    3. _dispatcherTimer = new Timer(timerDelegate, null, 0, 1000);
    4. ProgressDialog progressDialog = ProgressDialog.Show(this, "", "请稍后...");
    5. new Thread(new ThreadStart(() =>
    6. {
    7. string url = this.GetString(Resource.String.url) + "/AppServices/userServices.aspx?action=regSms";
    8. using (var http = new HttpClient())
    9. {
    10. var content = new FormUrlEncodedContent(new Dictionary<string, string>() {
    11. { "phone",userphone.Text }
    12. });
    13. var response = http.PostAsync(url, content);
    14. string me = response.Result.Content.ReadAsStringAsync().Result;
    15. progressDialog.Dismiss();
    16. this.RunOnUiThread(() =>
    17. {
    18. HandleResult(me);
    19. });
    20. }
    21. })).Start();
    22. }