0
返回值我創建了一個類來檢查設備互聯網接入,我的類別代碼被如何創建一個布爾方法從處理器
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;
}
但問題是,它總是返回我老的狀態值,因爲當線程運行時,該方法給我的老狀態值。 我想獲得更新的狀態值。
將其Android設備上工作?公共靜態布爾測試() \t { \t \t嘗試{ \t \t \t的InetAddress的InetAddress = InetAddress.getByName( 「www.google.com」); \t \t \t如果(inetAddress.isReachable(1000)) \t \t \t { \t \t \t \t的System.out.println( 「連接」); \t \t \t \t return true; \t \t \t \t \t \t \t} \t \t \t別的 \t \t \t { \t \t \t \t的System.out.println( 「未連接」); \t \t \t \t return false; \t \t \t} \t \t}趕上(例外五){ \t \t \t // TODO自動生成的catch程序塊 \t \t \t e.printStackTrace(); \t \t \t System.err.println(e.getMessage()); \t \t \t return false; \t \t} \t}此代碼顯示未連接,但我的設備已連接。 – kaibuki 2011-12-16 09:33:01