Question

I've got a little problem.. i have a wifi toggle and i can enable it or disable it. I'm saving the toggle state with sharedpreferences and in the onCreate i wrote this code:

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). 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? Thanks.

Was it helpful?

Solution

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. 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. The exclusive or will not check the second condition as TRUE || FALSE = TRUE and TRUE || TRUE = TRUE. The outcome in this case only depends on the first parameter. Fix for your if then else construct:

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

OTHER TIPS

Determining and Monitoring the Connectivity Status

Check this

Below is the code to check wifi enabled or not :-

            boolean wifiEnabled = AndroidGPSTrackingActivity.wifiManager.isWifiEnabled();

If wifi is enabled check :-

// if WIFI Enabled get lat/long using WIFI Services
        if (wifiEnabled) {
            //do something
            Log.d("Network", "Network");
            }
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top