Reputation: 699
I have a toggle button to turn on and off wireless. It works fine. But, I want when I enter my app, if wireless is already on, my toggle button to be on as well. Now it's not. Something is not right. Here's my code.
WifiManager WifiMan;
ToggleButton WiFi, GPRS;
WiFi.setOnClickListener(new OnClickListener() { //Ukljucuje WiFi
@Override
public void onClick(View v) {
if(WifiMan.isWifiEnabled())
{
WiFi.setEnabled(true);
}
else{
WiFi.setEnabled(false);
}
try
{
if (((ToggleButton)v).isChecked())
SwarmPopup.this.WifiMan.setWifiEnabled(true);
else
SwarmPopup.this.WifiMan.setWifiEnabled(false);
}
catch (Exception localException)
{
Log.e("SwarmPopup", "error on WiFi listerner: " + localException.getMessage(), localException);
}
}
});
}
Upvotes: 0
Views: 399
Reputation: 86948
Assuming WifiMan
is a WifiManager, then use:
WiFi.setChecked(WifiMan.isWifiEnabled());
Also please read about Java naming convention which states that variables names should start with lowercase letters.
Lastly, code like this:
if(WifiMan.isWifiEnabled())
{
WiFi.setEnabled(true);
}
else{
WiFi.setEnabled(false);
}
Can be simplified to:
WiFi.setEnabled(WifiMan.isWifiEnabled());
Upvotes: 2
Reputation: 67199
If that is all of your code (I doubt it is), then the problem is that you are only checking for WiFi status (and your toggle status) when the toggle is clicked.
If you add a check for WiFiMan.isWifiEnabled()
in your Activity's onCreate()
, you can easily set the toggle's status when the Activity is created.
Upvotes: 2