0

以下のコードを使用して、Android で接続タイムアウトを確認しています。これに加えて、接続が実際にタイムアウトした場合にトーストを表示するにはどうすればよいですか? なにか提案を?

/*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();    
}

アクティビティから適切なコンテキストを渡すようにしてください。

お役に立てれば。

于 2014-10-07T08:05:02.933 に答える