如何检查 Phone 上是否启用了 WiFi

How To Check if WiFi Enabled On Phone

我正在尝试使用 java 和 xml 开发一个 android 应用程序,我想要一些关于如何确定 [=16] 上是否启用了 wifi 的指导=] 该应用程序是否打开。任何帮助,将不胜感激。我试过使用这些方法,但它们都无法检测我的 wifi 端口是否正确打开或关闭。恐怕这些方法已经过时了。有人有最新的方法吗?

//determine if wifi is enabled
    //1st try
    wifi =Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON);

    //second try
    wifi=Settings.Global.getInt(cr, Settings.Global.WIFI_ON, 0);

    //3rd try
    WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
    if (wifi.isWifiEnabled()){
        //wifi is enabled
        wifiInt=1;
    }
    else
        wifiInt=0;

可以通过获取 WiFi 系统服务实例来检查 WiFi 状态,如下所示:

WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);

由此,可以使用方法isWifiEnabled()来判断WiFi是否开启。如下:

WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()){
    //TODO: Code to execute if wifi is enabled.
}

WiFi和移动数据都可以这样查看..

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mData = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if(mWifi.isConnected()||mData.isConnected()){
    //Do something when data is available
}

检查任何活动的网络连接:

private boolean isNetworkAvailable() {

        //Call this method to check network connection.

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();

    }

你也可以尝试获取wifi连接的wifi名称

WifiManager wifiManager = (WifiManager)HomeScreen.this.getSystemService(Context.WIFI_SERVICE);
            if(wifiManager != null) 
            {
                if(wifiManager.isWifiEnabled())
                {
                    WifiInfo connectedWifiInfo = wifiManager.getConnectionInfo();
                    if(connectedWifiInfo != null)
                    {
                        if(connectedWifiInfo.getBSSID() != null)
                        {   
                            // connected
                        }
                        else
                        {
                            // not connected
                        }
                    }
                    else
                    {
                        // not connected
                    }
                }
                else
                {
                    // not connected
                }
            }