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方法ide

還有另外的方式ui

 

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上執行this

 

訪問網絡須要給permission,在項目屬性裏,Android Manifest 下面列出了全部的permission,打鉤internetspa

相關文章
相關標籤/搜索