我正在创建一个使用异步任务来登录和发送数据的Android应用程序(HTTP Post Request。当互联网连接良好时,应用程序正常工作但是在登录时由于连接速度慢而需要很长时间才能发布数据关闭。我想在这种情况下显示吐司“错误连接”。请帮助
答案 0 :(得分:0)
您的应用程序可能崩溃,因为您试图在UI线程中显示Toast。也就是说,您始终应该使用Handler或在onPostExecute()方法中对UI进行任何更改,该方法也在UI线程中运行。
如何在doInBackground的线程中捕获异常并在UI中表示它们线程是另一个问题,我可以建议你这个解决方案:
private class LoginTask extends
AsyncTask<Void, Integer, JSONArray[]> {
private static final int NETWORK_NO_ERROR = -1;
private static final int NETWORK_HOST_UNREACHABLE = 1;
private static final int NETWORK_NO_ACCESS_TO_INTERNET = 2;
private static final int NETWORK_TIME_OUT = 3;
// You can continue this list...
Integer serverError = NETWORK_NO_ERROR;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show(); // Don't forget to create it before
}
@Override
protected JSONArray[] doInBackground(Void... v) {
JSONArray[] result = null;
try {
result = NetworkManager.login(/* All params you need */);
} catch (JSONException e) {
return null;
} catch (ConnectException e) {
serverError = NETWORK_NO_ACCESS_TO_INTERNET;
return null;
} catch (UnknownHostException e) {
serverError = NETWORK_HOST_UNREACHABLE;
return null;
} catch (SocketTimeoutException e) {
serverError = NETWORK_TIME_OUT;
return null;
} catch (URISyntaxException e) {
// ..
return null;
} catch (ClientProtocolException e) {
// ..
return null;
} catch (Exception e) {
// ..
return null;
}
return result;
}
@Override
protected void onPostExecute(JSONArray[] result) {
progressDialog.dismiss();
if (result != null) {
processAndShowResult(result);
} else {
switch (serverError) {
case NETWORK_NO_ERROR:
Toast.makeText(YourActivity.this, "Probably, invalid response from server", Toast.LENGTH_LONG).show();
break;
case NETWORK_NO_ACCESS_TO_INTERNET:
// You can customize error message (or behavior) for different type of error
case NETWORK_TIME_OUT:
case NETWORK_HOST_UNREACHABLE:
Toast.makeText(YourActivity.this, "Error in Connection", Toast.LENGTH_LONG).show();
break;
}
}
}
}
通过这种方式,您可以根据这些错误灵活地控制网络错误并采取适当的措施。