8

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:

  1. onAvailable()
  2. onCapabilitiesChanged()
  3. onBlockedStatusChanged (blocked: false)
  4. onCapabilitiesChanged()
  5. 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.

5
  • Ugh. Do you have a specific OnePlus model (or models) that exhibits this behavior? Commented Mar 12, 2020 at 18:57
  • 2
    I tried with 4 different models out of that 3 OnePlus 6t devices with android 10 OS and one OnePlus 7 pro with android 10 all behaved the same way.
    – Jayanth
    Commented Mar 12, 2020 at 18:59
  • 2
    Please check below link, - forums.oneplus.com/threads/… - issuetracker.google.com/issues/143549613 Commented Apr 23, 2020 at 11:03
  • 2
    This issue happened with me and make me frustrated. I was testing using Samsung s10 and I searched a lot and found nothing. Then I tried another device and found it working as a charm. I looked for Samsung S10 devices if they have an issue at it seems there is a lot of issues reported since Android 10 update. If you are using S10 please check the following link, (the third solution works for me): thedroidguy.com/… Commented Jul 14, 2020 at 16:23
  • 1
    I have the same issue. I have tested on a Samsung S9+ and a Galaxy S6 tablet. Both have the same issue. Connect to the chosen wifi ssid (as entered in the specifier), the callback goes to onAvailable and is 'connected', but disconnects immediately. Both are API 29. (Q, 10) I have tried many combinations of the request modifiers as per numerous SO answers. I have used 3 different wifi connections, 2 on a router (wep and wpa) and one from a D1 mini AP. So far nothing works. All research in docs, online forums, and here on SO has led nowhere so far.
    – Eric Engel
    Commented Nov 13, 2020 at 4:39

4 Answers 4

3

I have been tracking & researching this a lot. All my findings along with my current most optimal solution can be found here

But more specific to your question is the following info taken from the link

As stated here by Google, some OEM Roms are not 'holding on to the request' and therefore the connection is dropping instantly. OnePlus have fixed this problem in some of their later models but not all. This bug will continuously exist for certain phone models on certain Android builds, therefore a successful fallback (i.e. a manual connection with no network disruption) is required. No known workaround is available

  • removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) wont help keep the connection on a OnePlus as stated here

  • setting the Bssid wont help keep the connection on a OnePlus as stated here

  • google cannot help, they have stated it is out of their hands here

  • OnePlus forum posts confirming it working for some models (but not all) after an update, see here, here & here

0
2

This issue still doesn't seem to be fixed as of September 2020 on certain devices, Oneplus 6, Nokia phones etc seem to be exhibiting this success connection loop. In the meantime if you have a iOT device your app is trying to auto connect and it fails you can try this in the onFail(), to dismiss the connection dialog and take your users gracefully to the wifi page to manually connect.

        connectivityManager.bindProcessToNetwork(null);
        connectivityManager.unregisterNetworkCallback(networkCallback);
        AlertDialog.Builder alert = new AlertDialog.Builder(...);
        alert.setTitle(...);
        alert.setMessage(...);
        alert.setPositiveButton("OK",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
              Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
              intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              context.startActivity(intent);
            }
          });
        alert.show();
      }
1
  • 1
    I'm testing with a Nokia phone, and I am experiencing this connection loop. However, it only happens if I call connectivityManager.unregisterNetworkCallback(networkCallback). If I do not unregister the callback, the phone stays connected to the WiFi. Not quite sure why...
    – Hayuki
    Commented Nov 10, 2020 at 11:46
2

Late to the conversation but, have you tried calling connectivityManager.bindProcessToNetwork(network) whenever you find an available network?

Here's an example of what I mean based on your question's 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) {
                super.onAvailable(network);

                // This is the new line of code
                ConnectivityManager.bindProcessToNetwork(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"));
                    }
                }

            }
...
}
1
  • ConnectivityManager.bindProcessToNetwork(network); solved my problem Commented May 29, 2021 at 4:06
1

If you are trying to connect to a network that does not provide access to the internet, instead of

NetworkRequest request = new NetworkRequest.Builder()
 .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
 .setNetworkSpecifier(specifier)
 .build();

try

NetworkRequest request = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(specifier)
.build()

Apparently, internet capability is required by default.

The documentation (see https://developer.android.com/reference/android/net/wifi/WifiNetworkSpecifier.Builder#build()) says

Create a specifier object used to request a local Wi-Fi network. The generated NetworkSpecifier should be used in NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier) when building the NetworkRequest. These specifiers can only be used to request a local wifi network (i.e no internet capability). So, the device will not switch it's default route to wifi if there are other transports (cellular for example) available.

I don't really understand this paragraph, but it talks about the device switching back to the default route, what would cause a disconnection from your target network.

The example that is provided there includes the line

.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)

I copied the example and it worked for me. Never tried to make the connection without the line above.

However, I only had tried to connect to a network with internet connection. To my surprise, when I tried to connect to one without it, in spite of the documentation, the connection fails.

2
  • What device did you try it on? I've tried that line and it doesn't work on my Samsung S9+. Tried connecting to my network connected to the internet and also softAP without internet. Neither would work for me.
    – Eric Engel
    Commented Nov 18, 2020 at 2:42
  • Galaxy A10s. It works when there is internet, but only now I disconnected the cable and tried without internet. In contrast to what the documentation said, it failed.
    – jesjf
    Commented Nov 18, 2020 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.