Android 打开系统热点

希望这篇文章可以帮助到正好需要的你。


public class WirelessHotspot {
    private static WifiManager wifiManager;
    private static String Name = "启明3";
    private static String Pwd = "12345678";

    
 

    public enum WIFI_AP_STATE {
        WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_ENABLING, WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_FAILED
    }
    //判断当前热点是否开启关闭
    public static boolean isWifiApEnabled(Context context) {
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return getWifiApState() == WIFI_AP_STATE.WIFI_AP_STATE_ENABLED;
    }

    private static WIFI_AP_STATE getWifiApState() {
        int tmp;
        try {
            Method method = wifiManager.getClass().getMethod("getWifiApState");
            tmp = ((Integer) method.invoke(wifiManager));
            if (tmp > 10) {
                tmp = tmp - 10;
            }
            return WIFI_AP_STATE.class.getEnumConstants()[tmp];
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return WIFI_AP_STATE.WIFI_AP_STATE_FAILED;
        }
    }
    //设置热点是否开启关闭
    public static boolean setWifiApEnabled(boolean enabled) {
        if (enabled) {
            wifiManager.setWifiEnabled(false);//关闭wifi
        }
        try {
            WifiConfiguration apConfig = new WifiConfiguration();
            apConfig.SSID = Name;//热点名称
            apConfig.preSharedKey = Pwd;//热点密码
            apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);//加密
            Method method = wifiManager.getClass().getMethod(
                    "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
            return (Boolean) method.invoke(wifiManager, apConfig, enabled);
        } catch (Exception e) {
            return false;
        }
    }
}

你可能感兴趣的:(Android开发)