我创建了一个类来检查设备上的互联网访问,我的类代码是
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();
}
}
我想创建一个公共静态布尔方法,它返回状态,我已经提出了一些代码
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;
}
但问题是它总是返回旧的状态值,因为在线程运行的时候,该方法会向我发送旧的状态值。 我想获得更新的状态值。
答案 0 :(得分:3)