我的Xamarin Android應用程序使用Web服務,它使用HttpClient連接到它。在沒有連接的情況下(例如,當用戶沒有小區或WiFi連接時),會引發一些問題。我使用async/await從服務器獲取數據。下面是從我的代碼的摘錄:在HttpClient異常(Xamarin Android)上顯示AlertDialog
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;
}
我定義了一個custon 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警報。 – Jason