android my device connected with wifi but how to if wifi is connected but these is no internet connection
following is my code that i trying to check if no internet connection
public static boolean isConnectedWifi(Context context) {
NetworkInfo info=null;
if(context!=null){
info= IsNetConnectionAvailable.getNetworkInfo(context);
}
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
it always return true when no internet access
NetworInfo.isAvailable
and NetworkInfo.isConnected
only indicate whether network connectivity is possible or existed, they can't indicate whether the connected situation has access to the public internet, long story short, they can't tell us the device is online indeed.
To check whether a device is online, try the following methods:
First:
@TargetApi(Build.VERSION_CODES.M)
public static boolean isNetworkOnline1(Context context) {
boolean isOnline = false;
try {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities capabilities = manager.getNetworkCapabilities(manager.getActiveNetwork()); // need ACCESS_NETWORK_STATE permission
isOnline = capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
} catch (Exception e) {
e.printStackTrace();
}
return isOnline;
}
Strength: 1. could run on UI thread; 2. fast and accurate.
Weakness: need API >= 23 and compatibility issues.
Second:
public static boolean isNetworkOnline2() {
boolean isOnline = false;
try {
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("ping -c 1 8.8.8.8");
int waitFor = p.waitFor();
isOnline = waitFor == 0; // only when the waitFor value is zero, the network is online indeed
// BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
// String str;
// while ((str = br.readLine()) != null) {
// System.out.println(str); // you can get the ping detail info from Process.getInputStream()
// }
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return isOnline;
}
Strength: 1. could run on UI thread; 2. you can ping many times and do statistics for min/avg/max delayed time and packet loss rate.
Weakness: compatibility issues.
Third:
public static boolean isNetworkOnline3() {
boolean isOnline = false;
try {
URL url = new URL("http://www.google.com"); // or your server address
// URL url = new URL("http://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection", "close");
conn.setConnectTimeout(3000);
isOnline = conn.getResponseCode() == 200;
} catch (IOException e) {
e.printStackTrace();
}
return isOnline;
}
Strength: could use on all devices and APIs.
Weakness: time-consuming operation, can't run on UI thread.
Fourth:
public static boolean isNetworkOnline4() {
boolean isOnline = false;
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("8.8.8.8", 53), 3000);
// socket.connect(new InetSocketAddress("114.114.114.114", 53), 3000);
isOnline = true;
} catch (IOException e) {
e.printStackTrace();
}
return isOnline;
}
Strength: 1. could use on all devices and APIs; 2. relatively fast and accurate.
Weakness: time-consuming operation, can't run on UI thread.
check with the below set of codes.
public boolean isNetworkAvailable(Context context) {
boolean isOnline = false;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NetworkCapabilities capabilities = manager.getNetworkCapabilities(manager.getActiveNetwork());
isOnline = capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
} else {
NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
isOnline = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
} catch (Exception e) {
e.printStackTrace();
}
return isOnline;
}
After searching for days and after trying various solutions, some are not perfect some are too LONG, below is a solution suggested by LEVIT using SOCKETS which is PERFECT to me. Any one searching on this solution may consult this post. How to check internet access on Android? InetAddress never times out
Below is the portion of the code with example of task in AsyncTask
class InternetCheck extends AsyncTask<Void,Void,Boolean> {
private Consumer mConsumer;
public interface Consumer { void accept(Boolean internet); }
public InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); }
@Override protected Boolean doInBackground(Void... voids) { try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
sock.close();
return true;
} catch (IOException e) { return false; } }
@Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); }
}
///////////////////////////////////////////////////////////////////////////////////
// Usage
new InternetCheck(internet -> { /* do something with boolean response */ });
Below is a summary related to the solution Possible Questions Is it really fast enough?
Yes, very fast ;-)
Is there no reliable way to check internet, other than testing something on the internet?
Not as far as I know, but let me know, and I will edit my answer.
What if the DNS is down?
Google DNS (e.g. 8.8.8.8) is the largest public DNS in the world. As of 2013 it served 130 billion requests a day. Let 's just say, your app would probably not be the talk of the day.
Which permissions are required?
<uses-permission android:name="android.permission.INTERNET" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With