1

I know that to switch Wi-Fi state I have to do this:

wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

and write the following permissions:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

I made two radio buttons (on/off) and they goes but it's not the best solution, so I want to create a toggle button. How can I put the code inside a toggle button?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Atlas91
  • 5,754
  • 17
  • 69
  • 141

2 Answers2

3

You could do this in your Activity :

public class MyActivity extends Activity {

    private ToggleButton btn;
    private WifiManager wifiManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);

        btn = (ToggleButton) findViewById(R.id.btn_id);
        btn.setChecked(wifiManager.isWifiEnabled());

        btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                wifiManager.setWifiEnabled(isChecked);
            }

        });
    }
}

Check the ToggleButton documentation.

Laurent Dezitter
  • 710
  • 1
  • 8
  • 16
  • This is a button right? Because i'm looking for a toggle solution – Atlas91 Jun 14 '13 at 14:02
  • 1
    Nice nice thanks.. This example is only to enable the wifi? have i to make the same but instead of `btn.setChecked(enabled);` will be `btn.setChecked(disabled);` or not? – Atlas91 Jun 14 '13 at 14:25
  • 1
    _isChecked_ will be set to true if the state is checked, false otherwise. See [CompoundButton.OnCheckedChangeListener](http://developer.android.com/reference/android/widget/CompoundButton.OnCheckedChangeListener.html) – Laurent Dezitter Jun 14 '13 at 14:49
  • So this is all right? When toggle's check wifi starts and when toggle's off stops right? – Atlas91 Jun 14 '13 at 14:51
0

To actually toggle, meaning, switching the state, use:

WifiManager wm = ((WifiManager) activity.getSystemService(Context.WIFI_SERVICE));
wm.setWifiEnabled(!wm.isWifiEnabled());
Oded Breiner
  • 28,523
  • 10
  • 105
  • 71