Detect if connection is wifi, 3G or EDGE in android?

前端 未结 3 465
面向向阳花
面向向阳花 2020-12-23 22:22

I need to detect in android if there is any connection Wifi or 3G ( or 3G+) or EDGE in android. When there is an connecti

3条回答
  •  醉话见心
    2020-12-23 22:53

    public class WifiState {
    
        Context context;
    
        public WifiState(Context context) {
            this.context = context;
        }
    
        public void haveNetworkConnection() {
    
            boolean haveConnectedWifi = false;
            boolean haveConnectedMobile = false;
    
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(context.CONNECTIVITY_SERVICE);
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                    if (ni.isConnected())
                        haveConnectedWifi = true;
                if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    if (ni.isConnected())
                        haveConnectedMobile = true;
    
            }
            if (haveConnectedWifi == false && haveConnectedMobile == false) {
    
                //do something to handle if wifi & mobiledata is disabled
    
            } else {
                     //do something else..
            }
        }
    

提交回复
热议问题