我修改了以前的代码 - 这段代码运行正常。唯一的问题是,在启动它之后,在第一次单击时它总是显示输出:
“互联网不可用”
但是第二次点击它会显示正确的输出。
public class MainActivity extends Activity {
boolean pingCheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
public void run() {
pingCheck = isURLReachable(getApplicationContext());
}
});
t.start();
if(pingCheck)
{
Toast.makeText(MainActivity.this,"Network is available",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this,"Network not available",Toast.LENGTH_LONG).show();
}
}
});
}
static public boolean isURLReachable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://google.com"); // Change to "http://google.com" for www test.
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout( 1000); // 10 s.
urlc.connect();
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
Log.wtf("Connection", "Success !");
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
return false;
}
}
答案 0 :(得分:0)
您无法在线程中运行异步任务,并在此之后立即检查结果。您需要等待任务完成。我建议您将回调传递给ping检查,一旦回调返回,请在if(pingCheck)
之后运行您的代码。
这应该做的工作:
public static interface OnInternetCheckCallback {
void onInternetCheckResult(boolean available);
}
public static void hasInternetAccess(OnInternetCheckCallback callback) {
new AsyncTask<OnInternetCheckCallback, Void, Boolean>() {
private OnInternetCheckCallback mCallback;
@Override
protected Boolean doInBackground(OnInternetCheckCallback... params) {
mCallback = params[0];
try {
URL checkUrl = new URL(HEALTHCHECK_URL);
HttpURLConnection connection = (HttpURLConnection) checkUrl.openConnection();
connection.setRequestProperty("User-Agent", "Android");
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(1500);
connection.connect();
return (connection.getResponseCode() == 200 && connection.getContentLength() <= 0);
} catch (IOException e) {
Log.e(TAG, ".doInBackground() - Error checking internet connection", e);
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
mCallback.onInternetCheckResult(result);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, callback);
}
此外,可能更好的办法是检查您自己的服务器,而不是google.com
,因为某些国家/地区的Google服务器已被屏蔽。