[英]android how to check wifi is connected but no internet connection
android my device connected with wifi but how to if wifi is connected but these is no internet connection android 我的设备已连接 wifi 但如何连接 wifi 但这些没有互联网连接
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当没有互联网访问时它总是返回true
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. NetworInfo.isAvailable
和NetworkInfo.isConnected
仅表示网络连接是否可能或存在,它们不能表示连接的情况是否可以访问公共互联网,长话短说,它们不能告诉我们设备确实在线。
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;优点: 1.可以在UI线程上运行; 2. fast and accurate. 2.快速准确。
Weakness: need API >= 23 and compatibility issues.弱点:需要 API >= 23 和兼容性问题。
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;优点: 1.可以在UI线程上运行; 2. you can ping many times and do statistics for min/avg/max delayed time and packet loss rate. 2.可以ping多次,统计最小/平均/最大延迟时间和丢包率。
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.优势:可以在所有设备和 API 上使用。
Weakness: time-consuming operation, can't run on UI thread.缺点:操作耗时,不能在UI线程上运行。
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;优势: 1.可以在所有设备和API上使用; 2. relatively fast and accurate. 2.相对快速准确。
Weakness: time-consuming operation, can't run on UI thread.缺点:操作耗时,不能在UI线程上运行。
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;
}
The code you are using is just use to check if you are connected to wifi or not.您使用的代码仅用于检查您是否已连接到 wifi。 It doesn't check if that wifi is slow or not.它不会检查该 wifi 是否很慢。 (No internet means slow connection). (没有互联网意味着连接速度慢)。
I tried to use this code.我尝试使用此代码。 Here, I try to hit google.com and have set a connection timeout value.在这里,我尝试访问 google.com 并设置了连接超时值。 If here internet speed is good, then result returned is 200. So I check if the result code is 200 or not.如果这里网速好,那么返回的结果是200。所以我检查结果代码是否是200。 If not, I show an alert that there is slow internet connection.如果没有,我会显示互联网连接速度缓慢的警报。 Use it in an asyntask, and onPostExecute() check the value of returned result.在异步任务中使用它,并且 onPostExecute() 检查返回结果的值。
HttpURLConnection urlc = null;
try {
urlc = (HttpURLConnection) (new URL("http://www.google.com")
.openConnection());
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000); // choose your own timeframe
urlc.setReadTimeout(2000); // choose your own timeframe
try {
urlc.connect();
// returning connection code.
return (urlc.getResponseCode());
} catch (IOException e1) {
e1.printStackTrace();
}
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.在搜索了几天并尝试了各种解决方案之后,有些不完美,有些太长,下面是 LEVIT 使用 SOCKETS 建议的解决方案,这对我来说是完美的。 Any one searching on this solution may consult this post.任何搜索此解决方案的人都可以参考这篇文章。 How to check internet access on Android? 如何在Android上检查互联网访问? InetAddress never times out InetAddress 永远不会超时
Below is the portion of the code with example of task in AsyncTask下面是代码的一部分,其中包含 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?如果 DNS 关闭怎么办?
Google DNS (eg 8.8.8.8) is the largest public DNS in the world. Google DNS(例如 8.8.8.8)是世界上最大的公共 DNS。 As of 2013 it served 130 billion requests a day.截至 2013 年,它每天处理 1300 亿个请求。 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" />
To just check if you are connected to the internet by Wi-Fi, have a look at the snippet below:要检查您是否通过 Wi-Fi 连接到互联网,请查看以下代码段:
NetworkInfo getWifi(){
ConnectivityManager connManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi;
}
Check whether it is connected or not by;检查它是否连接;
if(getWifi().isConnected()) {
//wi-fi connected
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.