问题
How to know whether I'm connected to WiFi or ethernet in Android? In Android OS this is notified for thess icons
Does it exist a way to know it programmatically?
回答1:
http://developer.android.com/training/basics/network-ops/managing.html
ConnectivityManager cm = (ConnectivityManager) getActivity().
getSystemService(context.CONNECTIVITY_SERVICE);
And then you use:
cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_ETHERNET
or:
cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI
to check whether it is on Wifi or Ethernet.
Hope that helped.
回答2:
Is this enough?
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (Wifi.isConnected()) { return true; }
Also, to get wifi details:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getSSID()
回答3:
You should use ConnectivityManager
You can find how to use it here
回答4:
Thanks everybody
Just for avoid Exceptions (no network case). I share my tested code.
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;
}
来源:https://stackoverflow.com/questions/22302548/how-to-know-whether-android-is-connected-to-wifi-or-ethernet