Pergunta

How to know whether I'm connected to WiFi or ethernet in Android? In Android OS this is notified for thess icons enter image description here

Does it exist a way to know it programmatically?

Foi útil?

Solução 3

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;
}

Outras dicas

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.

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()

You should use ConnectivityManager

You can find how to use it here

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top