vs xamarin android 读取rest
private void Btn_Click(object sender, EventArgs e) { var u = FindViewById<EditText>(Resource.Id.editText1).Text; var p = FindViewById<EditText>(Resource.Id.editText2).Text; var progressDialog = ProgressDialog.Show(this, "Please wait...", "Checking account info...", true); var t=new Thread(new ThreadStart(delegate { var r = Api.CheckUser(u, p); if (r.HasValue) { RunOnUiThread(() => progressDialog.Hide()); AppConfig.Config.SetNowUserId(r.Value); StartActivity(typeof(MainActivity)); Finish(); } else { RunOnUiThread(() => Toast.MakeText(this, "用户名或密码错误", ToastLength.Long).Show()); RunOnUiThread(() => progressDialog.Hide()); } })); t.Start(); }
把loading框显示出来,然后开新线程做事,之后关闭loading框。
因为是开新线程,所以如果希望更新界面,需要使用 RunOnUiThread方法
还有另外的方式
private readonly TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
private void Btn_Click(object sender, EventArgs e) { var u = FindViewById<EditText>(Resource.Id.editText1).Text; var p = FindViewById<EditText>(Resource.Id.editText2).Text; var progressDialog = ProgressDialog.Show(this, "Please wait...", "Checking account info...", true); Task.Factory.StartNew(() => { return Api.CheckUser(u, p); }).ContinueWith(r => { progressDialog.Hide(); if (r.Result.HasValue) { AppConfig.Config.SetNowUserId(r.Result.Value); StartActivity(typeof(MainActivity)); Finish(); } else { Toast.MakeText(this, "用户名或密码错误", ToastLength.Long).Show(); } }, uiScheduler); }
使用Task的ContinueWith,可以指定在ui上执行
访问网络需要给permission,在项目属性里,Android Manifest 下面列出了所有的permission,打钩internet