I'm currently trying to connect to a wifi network. I used the below code.
WifiNetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
.setSsid(ssid)
.setBssid(MacAddress.fromString(bssid))
.setWpa2Passphrase(password)
.build();
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(specifier)
.build();
ConnectivityManager manager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
manager.requestNetwork(request, new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
ConnectivityManager.setProcessDefaultNetwork(network);
super.onAvailable(network);
NetworkInfo info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (info != null && info.isConnectedOrConnecting()) {
if (!emitter.isDisposed()) {
emitter.onSuccess(true);
}
} else {
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("OS Disconnected"));
}
}
}
@Override
public void onUnavailable() {
super.onUnavailable();
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("Could not connect Wifi"));
}
}
});
});
issue: the above code works well with Pixel phone and Nokia but on Oneplus devices, I get toast connection success toast and immediately after this wifi gets disconnected. wifi Symbol is visible very briefly in the status bar. In the next Moment, Wifi-Symbol is gone and the system Dialog is visible again, to connect to the wifi.
Have given below the permissions, and location permission is granted and it is enabled in the device also.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
When I debug the Callback it is going through the methods in this Order:
- onAvailable()
- onCapabilitiesChanged()
- onBlockedStatusChanged (blocked: false)
- onCapabilitiesChanged()
- onLost()
I have already referred these
Android Q, programmatically connect to different WiFi AP for internet
WiFi Network Connection keeps disconnecting on Android Q
Wifi Network Request Api connection issue in android 10 (Q)
Android Q, WifiNetworkSpecifier loosing Wifi immediately after connection is established
and I could not able to find a solution.
Is there anything I'm missing in network request that causes disconnection. or any other solution appreciated.
Thank you.