In AgroSense we need to know, if the computer is connected to the internet or not. And we don’t want to bother the user by throwing UnknownHostException or IOException also.
So we need two things:
- Check the connection
- Notify everybody interested, that the connectivity changed
When the first point is successfully implemented, the second one is easy – it is just a listener, so we will look only at the connectivity check problem.
Solution
For checking internet connectivity you need some host address. You will probably use the address, which you actually call, in our case it is www.openstreetmap.org.In first step, we check, if there is some internet connection, this is done in a method isOnlineFastCheck:
private boolean isOnlineFastCheck() {
boolean check = false;
try {
InetAddress.getByName(hostName);
check = true;
} catch (UnknownHostException e) {
//noop
}
return check;
}
This method checks, if we have an internet connection, but doesn’t say anything about connection to our desired server.
Knowing, that we are online (exactly connected to a DNS server) we can do another check, this time for the server:
private void doCheck() {
boolean oldOnline = online;
if (isOnlineFastCheck()) {
try (Socket socket = new Socket(hostName, portNumber)) {
online = (socket.getInputStream() != null);
} catch (Throwable e) {
online = false;
}
} else {
online = false;
}
if (oldOnline != online) {
propertyChangeSupport.firePropertyChange(PROPERTY_NAME, oldOnline, online);
}
}
Here we use the Socket class created for the server host name and port number and try to get the inputStream if stream is not null and no exception is thrown, we have connection to our server.
There is also used a propertyChangeSupport, so we can add a PropertyChangeListener to get notified whenever connectivity changes.
To have our goal complete we want to periodically call the check method. For this the Timer class is perfect:
Create TimerTask:
private TimerTask createTimerTask() {
return new TimerTask() {
@Override
public void run() {
doCheck();
}
};
}
Start and stop timer:
public void start() {
if (!started) {
timer = new Timer("onlineChecker", true);
timer.schedule(createTimerTask(), 0, checkPeriod);
started = true;
}
}
public void stop() {
if (started) {
timer.cancel();
timer = null;
started = false;
}
}
checkPeriod is set to 5000, so check happened every 5 seconds.
With all this code we can ask anytime, if our computer is online calling method:
public boolean isOnline() {
if (!isOnlineFastCheck()) {
return false;
} else {
return online;
}
}