check ethernet connection periodically android
I'm trying to periodically check the network connection. However, this is
for a Chinese Android Mini PC, not a tablet or smartphone. I'm using an
ethernet to usb adapter instead of Wi-Fi. First I used a 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's no network connectivity.");
}
}
}
This works perfectly for Wi-Fi and mobile. However, for ethernet, there
are complications. When I connect the ethernet to usb adapter, it thinks
it already has ETHERNET connection, whether the ethernet cable is
connected or not. Only when removing the adapter, it knows the ethernet
connection was removed.
I tried using a socket, and this kind of works:
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 perfectly and fast. When the
connection is lost, it takes way too long for the program to know it has.
I need this solution, but it should know way faster that the ethernet
connection has been lost. Also, this relies on Exceptions, which I'm not
fond of at all.
Lastly 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;
This should work, right? Unfortunately, it doesn't. Until now, I've always
received a false when executing this code.
What am I doing wrong and what is the correct way to do this?
No comments:
Post a Comment