I am trying to periodically check my network connection. However, this is for the Chinese Android Mini PC, and not for the tablet or smartphone. I am using ethernet adapter for usb instead of wifi. First I used the broadcastreceiver class:
public class NetworkStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getExtras() != null) { @SuppressWarnings("deprecation") NetworkInfo eni = (NetworkInfo) intent.getExtras().get( ConnectivityManager.EXTRA_NETWORK_INFO); if (eni != null && eni.getState() == NetworkInfo.State.CONNECTED) { Log.d(TAG, "Network " + eni.getTypeName() + " connected."); } } if (intent.getExtras().getBoolean( ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) { Log.d(TAG, "There no network connectivity."); } } }
This works great for Wi-Fi and mobile devices. However, there are complications for ethernet. When I connect ethernet to a USB adapter, it considers that it already has an ETHERNET connection, whether an Ethernet cable is connected or not . Only when removing the adapter does he know that the Ethernet connection has been removed.
I tried using a socket, and this kind of work:
private static boolean checkSocket(String host, int port) { Socket socket = null; boolean reachable = false; try { socket = new Socket(InetAddress.getByName(host), port); reachable = true; } catch (UnknownHostException e) { } catch (IOException e) { } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } return reachable; }
When there is a connection, it works fine and fast. When a connection is lost, it is too long for the program to know. I need this solution, but it should know the way faster that the Ethernet connection was lost. Also, it depends on the Exceptions, which I don't like at all.
Finally, I tried a simple ICMP message:
try { InetAddress address = InetAddress.getByName(host); if (address.isReachable(timeout)) { return true; } } catch (UnknownHostException e) { } catch (IOException e) { } return false;
That should work, right? Unfortunately not. So far, I always got false when executing this code.
What am I doing wrong and how to do it right?
EDIT 1
I tried this solution now, which works and does not work. This is funny and annoying as I test this on onResume() . After several correct attempts, he suddenly stops. I donβt even know why.
boolean reachable = false; try { Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 " + host); int retValue = p1.waitFor(); reachable = (retValue == 0); Log.d(TAG, String.valueOf(reachable)); p1.destroy(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return reachable;