android点击按钮打开wifi或者关闭wifi

1:写一个按钮实现点击

 Button
            android:id="@+id/btn_wifi"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/openwifi" /

代码实现

public class MainActivity extends AppCompatActivity {

    private WifiManager wifiManager;
    private LinearLayout btnWifi;

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

    }
    private void initData() {
        //获取wifi管理服务
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        btnWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取wifi开关状态
                int status=wifiManager.getWifiState();
                if (status == WifiManager.WIFI_STATE_ENABLED ) {
                    //wifi打开状态则关闭
                    wifiManager.setWifiEnabled(false);
                    Toast.makeText(MainActivity.this, "wifi已关闭", Toast.LENGTH_SHORT).show();
                }else {
                    //关闭状态则打开
                    wifiManager.setWifiEnabled(true);
                    Toast.makeText(MainActivity.this, "wifi已打开", Toast.LENGTH_SHORT).show();

                }
            }
        });
    }

    private void initView() {
        btnWifi = (LinearLayout) findViewById(R.id.btn_wifi);

    }
}
最新回复(0)
/jishua2cTt0cFQxyb_2FGoY1UpKEznMP8oNkyW_2FqetV9A_3D_3D8