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