如何在Android api级别23上以编程方式打开Wifi热点?

如何在Android api级别23上以编程方式打开Wifi热点?,android,android-6.0-marshmallow,hotspot,Android,Android 6.0 Marshmallow,Hotspot,该程序需要使用自定义SSID和密码打开热点,但我找不到任何API在棉花糖上执行此操作。您可以使用以下独立类: import android.content.*; import android.net.wifi.*; import java.lang.reflect.*; public class ApManager { //check whether wifi hotspot on or off public static boolean isApOn(Context con

该程序需要使用自定义SSID和密码打开热点,但我找不到任何API在棉花糖上执行此操作。

您可以使用以下独立类:

import android.content.*;
import android.net.wifi.*;
import java.lang.reflect.*;

public class ApManager {

    //check whether wifi hotspot on or off
    public static boolean isApOn(Context context) {
        WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
        try {
            Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(wifimanager);
        }
        catch (Throwable ignored) {}
        return false;
    }

    // toggle wifi hotspot on or off
    public static boolean configApState(Context context) {
        WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
        WifiConfiguration wificonfiguration = null;
        try {
            // if WiFi is on, turn it off
            if(isApOn(context)) {
                wifimanager.setWifiEnabled(false);
            }
            Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            method.invoke(wifimanager, wificonfiguration, !isApOn(context));
            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
现在,创建类后,将向清单中添加以下权限:

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

执行上述操作后,以下代码将切换热点:

ApManager.configApState(MainActivity.this)

您需要传递准确的上下文来代替
MainActivity。这将


我很久以前使用过这个类,但不记得它的来源。

仍然不起作用。什么也没发生。wifi刚刚关闭,仅此而已。您当前使用的是哪个android版本?我使用的是安卓6.0.1,MIUI8。