我正在使用此代码检查网络是否已连接。 在 8.1 的所有Android版本上均能完美运行 但是从Android Pie开始,它始终显示我没有连接!
private boolean isNetworkAvailable() {
final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnected()) {
onUpdateNetworkStatus(false);
return false;
}
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
final URL url = new URL("http://clients3.google.com/generate_204");
final HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", "Android");
httpURLConnection.setRequestProperty("Connection", "close");
httpURLConnection.setConnectTimeout(1500);
httpURLConnection.connect();
onUpdateNetworkStatus(httpURLConnection.getResponseCode() == 204 && httpURLConnection.getContentLength() == 0);
} catch (Exception e) {
onUpdateNetworkStatus(false);
}
}
});
thread.start();
return true;
}