![](/img/trans.png)
[英]How to check if mobile network is connected to the internet or not in android
[英]how to check the real Internet connected in android?
我制作一个程序,我必须使用wifi连接互联网。 我找到一些信息来检查wifi是否已连接。 但在某些情况下,你可以连接wifi AP,但你仍然无法使用互联网,如WiFi所需的帐户和密码到https的证书,或无线AP无法上网。 那么,我该如何检查真正的互联网连接?
只需对www.google.com进行“Ping”,他们失败的可能性非常低。
PS这是我们在我们的应用程序中做的..
public static boolean isReachable(Context context) {
// First, check we have connectivity
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
// check if google is reachable
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10 * 1000); // Ten seconds timeout in milliseconds
urlc.connect();
if (urlc.getResponseCode() == 200) { // success
return true;
} else { // Fail
return false;
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
return false;
}
} else {
return false;
}
}
请参阅以下内容:
创建一个返回布尔值的方法:
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
public Boolean checkNow(Context con){
try{
connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifiInfo.isConnected() || mobileInfo.isConnected())
{
return true;
}
}
catch(Exception e){
System.out.println("CheckConnectivity Exception: " + e.getMessage());
}
return false;
}
在onCreate()
方法中使用上面的方法,如下所示:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
boolean con = checkNow(getApplicationContext());
if(con){
Toast.makeText(getApplicationContext(), "Connection Founded", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Connection Not Founded", Toast.LENGTH_SHORT).show();
}
}
当您运行的应用程序,你会提示为"Connection Founded"
如果您的设备提供网络连接,否则会提示"Connection Not Founded"
。
根据以下方法,如果设备未处于飞行模式或在任何连接模式下没有网络可用,则方法将返回false,否则为true。 请记住,如果满足以上场景,它将返回null。 因此,它通过检查null netInfo对象来处理。
public boolean isOnline() {
ConnectivityManager conManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conManager .getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
请记住获得访问清单的网络状态的权限。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.