xamarin for android webservice


首先新建一個空網站,添加一個webservice服務。然后在UserWebService.cs類里編寫對外服務的方法

[WebMethod]
public string IsCorret(string  userName , string userPassWord) {
    if (userName.Equals("cjx") && userPassWord.Equals("123"))
    {
        return "True";
    }
    else
    {
        return "False";
    }   
}


在瀏覽器中運行下,判斷服務是否可以正常使用。確保可以正常使用后,在xamarin項目中WebReferences文件夾項右擊添加Web引用

 

 

在Activity類里編寫如下代碼,下面主要是在一個button事件中添加對webservice的調用

TextView tvUser = null;
TextView tvPassWord = null;
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Login);

    Button button = FindViewById<Button>(Resource.Id.into);
    button.Click += (sender, e) => {
        UserService.UserWebService us = new UserService.UserWebService();
        //webservice調用完成后觸發
        us.IsCorretCompleted += new UserService.IsCorretCompletedEventHandler(us_IsCorretCompleted);

        tvUser = FindViewById<TextView>(Resource.Id.accountNumber1);
        tvPassWord = FindViewById<TextView>(Resource.Id.password);
        us.IsCorretAsync(tvUser.Text, tvPassWord.Text);
    };          
}

 

當webservice方法執行完成的時候會觸發如下事件

void us_IsCorretCompleted(object sender, UserService.IsCorretCompletedEventArgs e)
{
    if (e.Result.Equals("True"))
    {
        //設置一個意圖
        var intent = new Intent(this, typeof(MainActivity));
        StartActivity(intent);
    }
    else {
        Toast.MakeText(this, "登錄失敗!", ToastLength.Short).Show();
    }
}


不過這樣子還是會出錯的,這里要感謝這篇文章的博主!

http://www.codeproject.com/Articles/641570/MonoAndroid-Using-dotnet-webservice-ASMX

通過這里的講解因為該項目是在android模擬器下運行的本地地址而是windows上的地址。於是不能使用localhost,而是要使用10.0.2.2

10.0.2.2 (Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine))

 

於是打開自動生產的類,修改下ip地址為10.0.2.2即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM