【问题标题】:Android how to show toast on Connection TimeOUTAndroid如何在连接超时时显示吐司
【发布时间】:2014-10-07 08:00:42
【问题描述】:

我正在使用下面的代码来检查 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 ??

【问题讨论】:

    标签: android networking toast connection-timeout http-response-codes


    【解决方案1】:

    您可以为此使用 try catch 块。

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

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

    希望这会有所帮助。

    【讨论】:

    • 我没有得到任何回应吗?我的意思是像“504”代码?
    • 我猜这将返回 response = null。 :) @user45678
    • 你确定吗?然后我可以直接检查空响应?
    • @user45678 您可以使用响应处理程序进行调试和检查,但我认为这不是检查空值的正确方法。特别是,当您可以更好地处理特定 ConnectionTimeoutException 的 try catch 时。
    猜你喜欢
    • 2014-05-13
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2013-10-14
    • 2016-12-16
    相关资源
    最近更新 更多