问题
Is there any way to find out that android device is connected to the Internet or not. I use this function:
public boolean isDeviceOnline() {
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
but this function return true if device connected to a WiFi network that doesn't include internet access or requires browser-based authentication and I want return false in this situation.
回答1:
try this
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isInternetAvailble() {
return isConnectingToInternet() || isConnectingToWifi();
}
private boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
private boolean isConnectingToWifi() {
ConnectivityManager connManager = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi != null) {
if (mWifi.getState() == NetworkInfo.State.CONNECTED)
return true;
}
return false;
} }
declare like this
ConnectionDetector ConnectionDetector = new ConnectionDetector(
context.getApplicationContext());
use like is
ConnectionDetector.isInternetAvailble()
回答2:
just try this method >
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null; // return true =(connected),false=(not connected)
}
回答3:
Change this:
return netInfo != null && netInfo.isConnectedOrConnecting();
To:
return netInfo != null && netInfo.isConnected();
Then call it like
if(!isDeviceOnline()) {
System.out.println("Not connected");
}
来源:https://stackoverflow.com/questions/45797996/how-i-can-check-android-device-is-connected-to-the-internet