【发布时间】:2016-04-08 10:10:30
【问题描述】:
我创建了一个方法来检查我的应用是否能够使用 OkHttp 连接到我的服务器。
这是我的测试课:
public class NetworkTest {
static boolean resultWeb = false;
public static boolean pingTestWeb() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.google.com")//My server address will go here
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
resultWeb = false;
Log.i("Error","Failed to connect: "+e.getMessage());
}
@Override
public void onResponse(Response response) throws IOException {
Log.i("Success","Success: "+response.code());
if (response.code() == 200) {
resulWeb = true;
}
}
});
return resultWeb;
}
这是我在 OnCreate() 上对我的活动进行测试的地方:
if (NetworkTest.pingTestWeb()) {
// Do something if true...
} else {
// Do something if false, like showing an AlertDialog...
}
问题是,我的 pingTestWeb 的默认超时时间为 10000 毫秒,如何让活动仅在 pingTestWeb 为 false 时创建 AlertDialog?因为它不等待响应。
【问题讨论】:
标签: android connection timeout ping okhttp