Android打开WIFI、关闭WIFI、检测当前WIFI状态

开启WIFI:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        WifiManager wifi =(WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        wifi.setWifiEnabled(true);
    }
});
关闭WIFI:

button2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        wifi.setWifiEnabled(false);
    }
});
获得WIFI状态:

button3.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        int wifiState = wifi.getWifiState();
        Toast.makeText(mContext, "状态是"+wifiState, Toast.LENGTH_SHORT).show();
    }
});
最后记得要在注册文件中加上权限

android:name="android.permission.CHANGE_WIFI_STATE" />
android:name="android.permission.ACCESS_NETWORK_STATE"/>
android:name="android.permission.ACCESS_WIFI_STATE"/>
android:name="android.permission.CHANGE_NETWORK_STATE"/>

你可能感兴趣的:(Android常见问题)