0

我正在使用下面的代码来检查 Android 中的连接超时。最重要的是,如果连接实际上超时,我该如何显示 Toast?有什么建议吗?

/*Client timeout*/
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000;        //3Seconds
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;            //5Seconds
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
/*Client timeout ends*/

final HttpClient client = new DefaultHttpClient(httpParameters);

**********************
//HOW TO SHOW TOAST MESSAGE WHEN THIS CASE ACTUALLY OCCURS ??
4

1 回答 1

1

您可以为此使用 try catch 块。

try{
    //your code of making request
}
catch (ConnectTimeoutException e) {
    Toast.makeText(context, "Connection timed out.", Toast.LENGTH_SHORT).show();    
}

确保从 Activity 传递正确的上下文。

希望这可以帮助。

于 2014-10-07T08:05:02.933 回答