Usman Riaz
Usman Riaz

Reputation: 3020

How to set secured hotspot in android (with password)

I want to set the hotspot on with it's ssid and password configured because i want to share it with some devices. The code i am using below works fine for me but i am unable to set the password of hotspot.

if (wm.isWifiEnabled()) {
                    wm.setWifiEnabled(false);
                }
                WifiConfiguration wifiCon = new WifiConfiguration();
                wifiCon.SSID = "UsmanAp";
                wifiCon.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                wifiCon.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                try{
                    Method setWifiApMethod = wm.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
                    boolean apstatus=(Boolean) setWifiApMethod.invoke(wm, wifiCon,true);
                    Method isWifiApEnabledmethod = wm.getClass().getMethod("isWifiApEnabled"); 
                    while(!(Boolean)isWifiApEnabledmethod.invoke(wm)){};
                    Method getWifiApStateMethod = wm.getClass().getMethod("getWifiApState"); 
                    int apstate=(Integer)getWifiApStateMethod.invoke(wm);
                    Method getWifiApConfigurationMethod = wm.getClass().getMethod("getWifiApConfiguration");
                    wifiCon=(WifiConfiguration)getWifiApConfigurationMethod.invoke(wm);
                } catch (Exception e) {
                    Log.e(this.getClass().toString(), "", e);
                }

What do add in the above code to set the password of the hotspot.

-Usman

Upvotes: 2

Views: 3144

Answers (1)

unrealsoul007
unrealsoul007

Reputation: 4077

You are not setting the preSharedKey, which is the password for WPA. Also the allowedKeyManagement should be set to WifiConfiguration.KeyMgmt.WPA_PSK.

WifiConfiguration wifiCon = new WifiConfiguration();
wifiCon.SSID = "UsmanAp";
wifiCon.preSharedKey = "password";
wifiCon.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiCon.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
try
{
    Method setWifiApMethod = wm.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
    boolean apstatus=(Boolean) setWifiApMethod.invoke(wm, wifiCon,true);
} 
catch (Exception e) 
{
    Log.e(this.getClass().toString(), "", e);
}

Upvotes: 8

Related Questions