我想在我的 Android 应用程序中实现一个 setConnectionTimeout。我遵循了几种代码结构,但无法使其工作。我的应用程序已连接到本地主机服务器,如果无法连接到数据库,我只希望它显示连接超时。
这是我的 Http 请求代码:
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;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
问题是当它达到 3 秒时,应用程序崩溃。在我实现这个片段之前,它只是冻结了更长的时间。如果我关闭我的 Wifi,它会返回一个对话框,说互联网没有连接,这就是我想要实现的。
如果无法连接数据库,知道如何返回 AlertDialogBox 吗?(为此我禁用了 WAMP)