How to know whether Android is connected to WiFi or ethernet? [closed]

自闭症网瘾萝莉.ら 提交于 2020-03-18 08:56:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!