[英]Android - checking if the device is connected to the internet
有沒有簡單的方法,如何檢查設備是否主動連接到互聯網(=通過GPRS,EDGE,UMTS,HSDPA或Wi-Fi連接)?
謝謝
是的,我使用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;
}
}
}
}
我在我的一個應用程序中使用它:
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return (ni != null && ni.isConnected());
}
您將在清單文件中需要這些權限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
您可以嘗試撤消本地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();
}
}
}
返回iNetAddress.getHostAddress()。toString(); 會給你IP地址。 您需要添加權限
<uses-permission android:name="android.permission.INTERNET" />
注意:如果您在仿真器中工作,它將重新調整仿真器IP(通常為10.0.2.15)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.