Android … how to find out if I'm on a wifi internet?

前端 未结 1 998
余生分开走
余生分开走 2021-01-07 11:25

In my application I just need to know if the device is connected to wifi network or not. I think this function works on emulator but not on real device.

pub         


        
相关标签:
1条回答
  • 2021-01-07 12:12

    Try this:

      public boolean isUsingWiFi() {
        ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
        NetworkInfo wifiInfo = connectivity
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
        if (wifiInfo != null && wifiInfo.getState() == NetworkInfo.State.CONNECTED
                || wifiInfo.getState() == NetworkInfo.State.CONNECTING) {
            return true;
        }
    
        return false;
    }
    

    You can also use the same for the mobile type:

      public boolean isUsingMobileData() {
        ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
        NetworkInfo mobileInfo = connectivity
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    
        if (mobileInfo != null && mobileInfo.getState() == NetworkInfo.State.CONNECTED
                || mobileInfo.getState() == NetworkInfo.State.CONNECTING) {
            return true;
        }
    
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题