1

我知道要切换 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>

我制作了两个单选按钮(开/关),它们会消失,但这不是最好的解决方案,所以我想创建一个切换按钮。如何将代码放在切换按钮中?

4

2 回答 2

3

您可以在 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);
            }

        });
    }
}

检查切换按钮文档

于 2013-06-14T13:57:59.247 回答
0

要实际切换,意思是切换状态,请使用:

WifiManager wm = ((WifiManager) activity.getSystemService(Context.WIFI_SERVICE));
wm.setWifiEnabled(!wm.isWifiEnabled());
于 2013-11-11T13:43:25.993 回答