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

转载于:https://www.cnblogs.com/czcz1024/p/4569764.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值