[英]Android - checking if the device is connected to the internet
is there any simple way, how to check if the device is actively connected into internet (= is connected via GPRS, EDGE, UMTS, HSDPA or Wi-Fi)? 有没有简单的方法,如何检查设备是否主动连接到互联网(=通过GPRS,EDGE,UMTS,HSDPA或Wi-Fi连接)?
Thanks 谢谢
Yes, I use isReachable. 是的,我使用isReachable。
public class Extras {
public static class Internet {
public static boolean isOnline() {
try {
InetAddress.getByName("google.ca").isReachable(3);
return true;
} catch (UnknownHostException e){
return false;
} catch (IOException e){
return false;
}
}
}
}
I use this in one of my apps: 我在我的一个应用程序中使用它:
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return (ni != null && ni.isConnected());
}
You will need these permissions in your Manifest file: 您将在清单文件中需要这些权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You can try retreaving the Local IP address to check whether device is connected to Internet. 您可以尝试撤消本地IP地址以检查设备是否已连接到Internet。
for (Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); enumeration.hasMoreElements();) {
NetworkInterface networkInterface = enumeration.nextElement();
for (Enumeration<InetAddress> enumIpAddress = networkInterface.getInetAddresses(); enumIpAddress.hasMoreElements();) {
InetAddress iNetAddress = enumIpAddress.nextElement();
if (!iNetAddress.isLoopbackAddress()) {
return iNetAddress.getHostAddress().toString();
}
}
}
The return iNetAddress.getHostAddress().toString(); 返回iNetAddress.getHostAddress()。toString(); will give you the IP address. 会给你IP地址。 You need to add permission 您需要添加权限
<uses-permission android:name="android.permission.INTERNET" />
Note: If you are working in Emulator it will retun the emulator IP (generally it will be 10.0.2.15) 注意:如果您在仿真器中工作,它将重新调整仿真器IP(通常为10.0.2.15)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.