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);
}
Call enableNetwork()
function on your wifiManager object, not WifiManager
class.
Be careful: the w letter should be lowercase.
Do the same for addNetwork()
.
In your manifest add these permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
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);
Add this line below wifiManager.setWifiEnabled(true)
line:
wifiManager.startScan();
If you need additional help, read this question and this article. Good Luck.