开发者

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

开发者 https://www.devze.com 2023-03-10 10:27 出处:网络
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.

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.

public static boolean wifiInternet(Context c)
{
    try
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)c.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = connectivityManager.getActiveNetworkInfo();  // CRASHES HERE
        String name = ni.getTypeName(); 
        if(name.equals("WIFI"))
            return true;
        else
            return false;
    }
    catch(Exception e开发者_如何学编程)
    {
        return false;
    }
}

And which context do I use here? getAplicationContext() or getBaseContext() or do I just put 'this' (I'm calling the function from a Service).


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

精彩评论

暂无评论...
验证码 换一张
取 消