【发布时间】:2017-08-28 20:47:02
【问题描述】:
我的 Xamarin Android 应用使用 Web 服务,它使用 HttpClient 连接到该服务。在没有连接时(例如,当用户没有手机或 WiFi 连接时),会抛出异常。我正在使用 async/await 从服务器获取数据。这是我的代码的摘录:
public async Task<String> doLogin(string username, string password)
{
String url = Constants.loginEndpoint + username + "/" + password + "/";
var uri = new Uri(string.Format(url, string.Empty));
return_string = "";
try
{
var response = await GetAsync(uri);
if (response.IsSuccessStatusCode)
{
return_string = "success";
// Process the positive response here
else
{ }
}
catch (Exception ex)
{
throw new ConnectionException();
}
return return_string;
}
我定义了一个自定义 ConnectionException 并希望向用户显示一个 AlertDialog 以通知他们请求由于没有连接而失败。用户单击确定后,我想关闭该应用程序。我尝试通过以下方式显示警报对话框,但它不起作用:
public class ConnectionException : Exception
{
public ConnectionException()
{
AlertDialog.Builder alert = new AlertDialog.Builder(myApp.Context);
alert.SetTitle("Failure");
alert.SetMessage("Request failed. No connection.");
alert.SetPositiveButton("OK", (senderAlert, args) =>
{
});
Dialog dialog = alert.Create();
dialog.Show();
}
public ConnectionException(string message)
: base(message)
{ }
public ConnectionException(string message, Exception innerException)
: base(message, innerException)
{ }
}
这是正确的方法吗?可能不会,因为它不起作用。对于如何实现这一目标,我将不胜感激。另外,我没有考虑太多,但这是处理此类异常的首选方式吗?
【问题讨论】:
-
异常对象本身不应该负责显示消息。您还(可能)尝试在后台线程上显示 UI 警报。
标签: c# android xamarin xamarin.android dotnet-httpclient