如何知道我是否已连接到Android中的WiFi或以太网? 在Android OS中,这会通知thess图标
是否存在以编程方式了解它的方法?
答案 0 :(得分:3)
这够了吗?
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (Wifi.isConnected()) { return true; }
另外,要获取wifi详细信息:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getSSID()
答案 1 :(得分:3)
http://developer.android.com/training/basics/network-ops/managing.html
ConnectivityManager cm = (ConnectivityManager) getActivity().
getSystemService(context.CONNECTIVITY_SERVICE);
然后你使用:
cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_ETHERNET
或:
cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI
检查它是否在Wifi或以太网上。
希望有所帮助。
答案 2 :(得分:1)
您应该使用ConnectivityManager
您可以找到如何使用它here
答案 3 :(得分:1)
谢谢大家
只是为了避免例外(没有网络案例)。我分享了我测试过的代码。
private Boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
public Boolean isWifiConnected(){
if(isNetworkAvailable()){
ConnectivityManager cm
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI);
}
return false;
}
public Boolean isEthernetConnected(){
if(isNetworkAvailable()){
ConnectivityManager cm
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_ETHERNET);
}
return false;
}