正确的方法来检查是否在Android中连接了Wifi

时间:2017-03-19 14:39:53

标签: android wifi android-wifi wifimanager android-connectivitymanager

对于我的应用,我需要确保用户在与服务器联系之前已连接到wifi。我找到了两种方法,但我不确定是否足够。

首先我要补充一下:

WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
            .getSystemService(WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
        buildAlertNoWifi();
        showProgressDialog(false, "");
        return;
}

然后我这样做:

ConnectivityManager cm = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) { // connected to the internet
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
            // connected to wifi

        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            // connected to the mobile provider's data plan
            Toast.makeText(getContext(), "Make sure you connect to wifi.", Toast.LENGTH_LONG).show();
            return;
        }
    } else {
        Toast.makeText(getContext(), "Make sure you connect to wifi.", Toast.LENGTH_LONG).show();
        return;
    }

所以我想知道wifiManager.isWifiEnabled()是否将设备连接返回到wifi或者只是打开了wifi。如果是这样,单独使用它是否足够?

3 个答案:

答案 0 :(得分:1)

最佳做法

public boolean isWifiConnected() {
    NetworkInfo net = getActiveNetworkInfo();
    return (isConnected(net) && net.getType() == TYPE_WIFI);
}

private NetworkInfo getActiveNetworkInfo() {
    ConnectivityManager connManager = (ConnectivityManager) MagazineApplication.getContext()
            .getSystemService(MagazineApplication.CONNECTIVITY_SERVICE);
    return connManager.getActiveNetworkInfo();
}

答案 1 :(得分:0)

我相信WifiManager.isWifiEnabled()只检查设备的wifi是否已打开。请使用NetworkInfo.isConnected()NetworkInfo.isConnectedOrConnecting()检查它是否已连接到任何网络。

答案 2 :(得分:0)

我相信这应该有用,

   public boolean isWifiConnected()
    {
        ConnectivityManager cm = (ConnectivityManager)this.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

        return (cm != null) && (cm.getActiveNetworkInfo() != null) &&
                (cm.getActiveNetworkInfo().getType() == 1);
    }