简体   繁体   English

检查是否启用了wifi和sharedpreferences

[英]Check if wifi is enabled and sharedpreferences

I've got a little problem.. i have a wifi toggle and i can enable it or disable it. 我有一个小问题。我有一个wifi切换开关,我可以启用或禁用它。 I'm saving the toggle state with sharedpreferences and in the onCreate i wrote this code: 我使用sharedpreferences保存切换状态,并在onCreate中编写了以下代码:

sPref  = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // Inizializzo la sharedpreferences
    ToggleButton wifitoggle = (ToggleButton) findViewById(R.id.wifitoggle); 
    boolean togglewifi = sPref.getBoolean("KEY", false);   
        if (togglewifi || wifiManager.isWifiEnabled()) 
        {

            wifitoggle.setChecked(true);
        }
            else
        {
            wifitoggle.setChecked(false);
        }

The state is saved and it goes well but as you can see i'm trying to check also if the wifi is enabled or not (For example enable it throught the android wifi settings and not from my application). 状态已保存并且运行良好,但是如您所见,我正在尝试检查是否启用了wifi(例如,通过android wifi设置而不是从我的应用程序启用它)。 Right now if i try to enable the wifi throught the settings and i open my application doesn't display that the wifi is enabled.. Something's wrong in the if condition? 现在,如果我尝试启用无线throught的设置,我打开我的应用程序不会显示该无线网络被启用..什么是错的if条件? Thanks. 谢谢。

This will not work in all cases as the user is enabled to change the Wifi state at every time and your application can not recognize this with your code. 这并非在所有情况下都可行,因为每次都允许用户更改Wifi状态,并且您的应用程序无法通过您的代码识别出此状态。 For example if togglewifi=true because you saved the state somewhere earlier then you set your button to checked but that does not mean that the wifi is enabled. 例如,如果togglewifi=true是因为您将状态保存在较早的位置,则将按钮设置为选中状态,但这并不意味着已启用wifi。 The exclusive or will not check the second condition as TRUE || FALSE = TRUE 异或不将第二个条件检查为TRUE || FALSE = TRUE TRUE || FALSE = TRUE and TRUE || TRUE = TRUE TRUE || FALSE = TRUETRUE || TRUE = TRUE TRUE || TRUE = TRUE . TRUE || TRUE = TRUE The outcome in this case only depends on the first parameter. 在这种情况下,结果仅取决于第一个参数。 Fix for your if then else construct: 修复您的if if else构造:

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
ToggleButton wifiToggle = (ToggleButton) findViewById(R.id.wifitoggle);
wifiToggle.setChecked(wifiManager.isWifiEnabled());

Determining and Monitoring the Connectivity Status 确定和监视连接状态

Check this 检查一下

Below is the code to check wifi enabled or not :- 以下是检查wifi是否启用的代码:-

            boolean wifiEnabled = AndroidGPSTrackingActivity.wifiManager.isWifiEnabled();

If wifi is enabled check :- 如果启用了wifi,请检查:-

// if WIFI Enabled get lat/long using WIFI Services
        if (wifiEnabled) {
            //do something
            Log.d("Network", "Network");
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM