Correct way to create hotspot programmatically in devices with Cyanogenmod (6.0+)

543 Views Asked by At
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;
}
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);
        }
        //Change Name of the Created Hotspot
        try {
            Method getConfigMethod = wifimanager.getClass().getMethod("getWifiApConfiguration");
            WifiConfiguration wifiConfig = (WifiConfiguration) getConfigMethod.invoke(wifimanager);                
            wifiConfig.SSID = "abcde123";
            wifiConfig.preSharedKey = "password123";                wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

            Method setWifiApMethod = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            boolean apstatus = (Boolean) setWifiApMethod.invoke(wifimanager, wifiConfig, true);

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        method.invoke(wifimanager, wificonfiguration, !isApOn(context));
        return true;
    }
    catch (Exception e) {
        e.printStackTrace();
    }

But when i run this code, hotspot is created but when clients turn to connect to it, it stucks on "Obtaining Ip Address" loop. Tested on CM13, CM14 for many devices. Please help me regarding this.

0

There are 0 best solutions below