Disconnect from a wifi network programmatically in Marshmallow


无法在棉花糖中以编程方式从wifi网络断开连接,找不到任何解决方案。如果任何人有任何解决方案将是巨大的帮助。谢谢

最佳答案

更新

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    wm.disconnect();


还为运行Android 6.0的设备在清单中以及运行时设置权限以更改Wifi状态

内部Manifest.xml

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


在运行时检查权限:

if (ActivityCompat.checkSelfPermission(SmsOtpCheck.this, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED)
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CHANGE_WIFI_STATE}, CODE);


批准或拒绝许可后:

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CODE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    //PERMISSION GRANTED
                else
                    Toast.makeText(this, "Permission not granted", Toast.LENGTH_SHORT).show();
        }
    }

07-27 17:44