Search code examples
androidandroid-wifiwifimanager

Automatically and programmatically connecting to a specific WiFi access point


I need to make my app connect automatically to specific SSID with password. I'm trying this but this is what I get:

error:

non-static method addNetwork(WifiConfiguration) cannot be referenced from a static context

error:

non-static method enableNetwork(int,boolean) cannot be referenced from a static context

final WifiManager wifiManager = (WifiManager) MainActivity.this.getSystemService(Context.WIFI_SERVICE);
final WifiConfiguration config = new WifiConfiguration();
config.SSID = "\"xxx\"";
config.preSharedKey = "\"123\"";
if (!wifiManager.isWifiEnabled()){
    wifiManager.setWifiEnabled(true);
    int networkId = WifiManager.addNetwork(config);
    WifiManager.enableNetwork(networkId, true);
}

Solution

  • Call enableNetwork() function on your wifiManager object, not WifiManager class.

    Be careful: the w letter should be lowercase.

    Do the same for addNetwork().

    EDIT:

    In your manifest add these permissions:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    

    EDIT 2:

    For WPA, update your config like this:

    config.status = WifiConfiguration.Status.ENABLED;
    
    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    
    config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    

    EDIT3:

    Add this line below wifiManager.setWifiEnabled(true) line:

    wifiManager.startScan();
    

    EDIT 4:

    If you need additional help, read this question and this article. Good Luck.