In Android socket programming, We need to judge the network status at all times. Android (Java) methods for determining the network status (isclosed (), isconnected (), isinputshutdown (), soutputshutdown () does not have a valid method. These are all used to determine the status of the local socket end. To determine the status of the remote socket end, you can send data to the other end through the interval, if an exception occurs during the sending process, the network is faulty.
The related methods are as follows:
Method 1: Try {socket. sendurgentdata (0xff);} catch (ioexception e) {// handlenetdisconnect (); E. printstacktrace ();}
Method 2:
/*** Send messages through TCP * @ Param Str */private Boolean sendmsg (string Str) {Boolean isconnect = false; If (dos! = NULL) Try {dos. write (Str. getbytes ("UTF-8"); dos. flush (); isconnect = true;} catch (ioexception e) {log. E ("tcpmsg", "writeoutputstream fail"); isconnect = false;} return isconnect ;}
The above two methods seem to be usable, but they are also invalid in some cases. For example, the network is disconnected from the other side (unplug the network cable ). In this case, other methods are required to determine the network status. We can use the Ping Command similar to the ping command in Windows to use the ping command in Linux, it is also a relatively accurate method.
Ping method in Android:
private boolean startPing(String ip){Log.e("Ping", "startPing...");boolean success=false;Process p =null; try { p = Runtime.getRuntime().exec("ping -c 1 -i 0.2 -W 1 " +ip); int status = p.waitFor(); if (status == 0) { success=true; } else { success=false; } } catch (IOException e) { success=false; } catch (InterruptedException e) { success=false; }finally{ p.destroy(); } return success;}
-C 1 indicates the number of sent messages, 1 indicates the number of sent messages, and-W indicates the waiting time for response after sending.
The above code can be used to test an IP address. A real machine is required for testing.