I have created a class to check access of internet on device, my class code is
public class CheckInternet {
private static Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
status = false;
System.out.println("Status False");
} else { // code if connected
status = true;
System.out.println("Status True");
}
}
};
private static void isNetworkAvailable(final Handler handler, final int timeout) {
new Thread() {
private boolean responded = false;
@Override
public void run() {
new Thread() {
@Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest); // can last...
responded = true;
} catch (Exception e) {}
}
}.start();
try {
int waited = 0;
while(!responded && (waited < timeout)) {
sleep(100);
if(!responded ) {
waited += 100;
}
}
}
catch(InterruptedException e) {} // do nothing
finally {
if (!responded) { handler.sendEmptyMessage(0);
}
else { handler.sendEmptyMessage(1);
}
}
}
}.start();
}
}
I want to create a public static boolean method which returns me the status, I have come up with some code
private static Boolean status = true ;
public static Boolean isConnected() {
Runnable runnable = new Runnable() {
public void run() {
// TODO Auto-generated method stub
isNetworkAvailable(h,2000);
}
};
runnable.run();
return status;
}
But the issue is that it always returns me the old status value, as while the time the thread is running, the method send me the old status value.
I want to get the updated status value.
You better use
isReachable(timeout)
http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html#isReachable%28java.net.NetworkInterface,%20int,%20int%29
Regards