我知道要切换Wi-Fi状态,我必须这样做:
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
并写下以下权限:
<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>
我制作了两个单选按钮(打开/关闭)但是它们不是最好的解决方案,所以我想创建一个切换按钮。如何将代码放在切换按钮内?
答案 0 :(得分:3)
您可以在您的活动中执行此操作:
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);
}
});
}
}
答案 1 :(得分:0)
要实际切换,意味着切换状态,请使用:
WifiManager wm = ((WifiManager) activity.getSystemService(Context.WIFI_SERVICE));
wm.setWifiEnabled(!wm.isWifiEnabled());