我有一个AsyncTask应该检查网络访问主机名.但是doInBackground()永远不会超时.有人有线索吗?
public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> {
private Main main;
public HostAvailabilityTask(Main main) {
this.main = main;
}
protected Boolean doInBackground(String... params) {
Main.Log("doInBackground() isHostAvailable():"+params[0]);
try {
return InetAddress.getByName(params[0]).isReachable(30);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean... result) {
Main.Log("onPostExecute()");
if(result[0] == false) {
main.setContentView(R.layout.splash);
return;
}
main.continueAfterHostCheck();
}
}
Run Code Online (Sandbox Code Playgroud) 我对android开发比较陌生.我正在开发一个Android应用程序,我正在向Web服务器发送请求并解析json对象.我经常java.net.SocketTimeoutException: Connection timed out在与服务器通信时遇到异常.有时它会毫无问题地完美运行.我知道这个问题在很多时候都被提出过.但我仍然没有得到任何满意的解决方案来解决这个问题.我正在下面发布我的logcat和app-server通信代码.
public JSONObject RequestWithHttpUrlConn(String _url, String param){
HttpURLConnection con = null;
URL url;
String response = "";
Scanner inStream = null;
PrintWriter out = null;
try {
url = new URL(_url);
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
if(param != null){
con.setFixedLengthStreamingMode(param.getBytes().length);
}
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
out = new PrintWriter(con.getOutputStream());
if(param != null){
out.print(param);
}
out.flush();
out.close();
inStream = new Scanner(con.getInputStream());
while(inStream.hasNextLine()){
response+=(inStream.nextLine());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch …Run Code Online (Sandbox Code Playgroud)