Connect to Wifi in Android Q programmatically

12,890

Solution 1

So, the solution for me is compile your app with targetSdkVersion 28. and for connection to wifi use this function

connectToWifi(String ssid, String key)

it's just a workaround for the moment, waiting Google to publish a fix for this bug, for more information the issue reported to Google : issuetracker.google.com/issues/138335744

public void connectToWifi(String ssid, String key) {

Log.e(TAG, "connection wifi pre Q");
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + ssid + "\"";
wifiConfig.preSharedKey = "\"" + key + "\"";
int netId = wifiManager.addNetwork(wifiConfig);
if (netId == -1) netId = getExistingNetworkId(wifiConfig.SSID);

    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect();
}

Solution 2

So far what is working for me on the majority of devices I have tested with, with a fallback option to at least stop the dreaded 'looping request' and to allow a successful manual connection

The below code is written in Kotlin, please google how to covert to Java if needed.

Create a NetworkCallback which is required for API >= 29 (prior it was not required but could be used)

val networkCallback = object : ConnectivityManager.NetworkCallback() {
    override fun onAvailable(network: Network) {
        super.onAvailable(network)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // To make sure that requests don't go over mobile data
            connectivityManager.bindProcessToNetwork(network)
        } else {
            connectivityManager.setProcessDefaultNetwork(network)
        }
    }

    override fun onLost(network: Network) {
        super.onLost(network)
        // This is to stop the looping request for OnePlus & Xiaomi models
        connectivityManager.bindProcessToNetwork(null)
        connectivityManager.unregisterNetworkCallback(networkCallback)
        // Here you can have a fallback option to show a 'Please connect manually' page with an Intent to the Wifi settings
    }
}

Connect to a network as follows:

val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
    .setSsid(ssid)
    .setWpa2Passphrase(pass)
    .build()

val networkRequest = NetworkRequest.Builder()
    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
// Add the below 2 lines if the network should have internet capabilities.
// Adding/removing other capabilities has made no known difference so far
//    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
//    .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
    .setNetworkSpecifier(wifiNetworkSpecifier)
    .build()

connectivityManager.requestNetwork(networkRequest, networkCallback)

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, but if found I will update it here as an option.

To remove the network, do the following:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    //This is required for Xiaomi models for disconnecting
    connectivityManager.bindProcessToNetwork(null)
} else {
    connectivityManager.setProcessDefaultNetwork(null)
}
connectivityManager.unregisterNetworkCallback(it)

Please keep in mind, an automatic connection allows for an automatic & manual disconnection. A manual connection (such as the suggested fallback for OnePlus devices) does not allow an automatic disconnection. This will also need to be handled within the app for a better UX design when it comes to IoT devices.

Some extra small tips & info:

  • now that a system dialog opens, the app calls onPause and onResume respectively. This affected my logic regarding automatic connection to IoT devices. In some case, onResume is called before the network callback is finished.

  • In regards to tests, I have yet to be able to get around the dialog by just using espresso and it may block some tests that were working before API 29. It may be possible using other frameworks such as uiautomator. In my case I adjusted the tests to work up until the dialog shows, and run further tests thereafter. Using Intents.init() does not work.

  • onUnavailable is called when the the network has been found, but the user cancels. It is not called when the network was not found or if the user cancels the dialog before the network has been found, in this case no other methods are called, use onResume to catch it.

  • when it fails on the OnePlus it called onAvailable() -> onCapabilitiesChanged() -> onBlockedStatusChanged (blocked: false) -> onCapabilitiesChanged() -> onLost() respectively

  • 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

  • when GPS is switched off, the SSID names of networks are not available

  • if the dialog comes several times, check your own activity lifecycle, in my case some models were calling onResume before the network callback was received.

  • manually connecting to a network without internet capabilities needs user confirmation to keep the connection (sometimes in the form of a dialog or as a notification), if ignored, the system will disconnect from the network shortly afterwards

List of devices tested:

  • Google Pixel 2 - No issues found
  • Samsung S10 SM-G970F - No issues found
  • Samsung S9 SM-G960F - No issues found
  • One Plus A5000 (OxegenOS 10.0.1) - Major Issue with automatic connection
  • HTC One M8 (LineageOS 17.1) - No issues found
  • Xiaomi Mi Note 10 - Issue with disconnecting (Fixed, see code example)
  • Samsung A50 - Dialog repetitively appears after successful connection (sometimes)
  • Huawei Mate Pro 20 - Dialog repetitively appears after successful connection (sometimes)
  • Huawei P40 Lite - Doesn't call onLost()
  • CAT S62 Pro - No issues found
  • Sony Xperia SZ2 - No issues found
  • Samsung Note10 - No issues found

Solution 3

In case if you want to connect to WiFi with INTERNET, you should use this kind of NetworkRequest:

NetworkRequest request = new NetworkRequest.Builder()
    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    .setNetworkSpecifier(wifiNetworkSpecifier)
    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
    .build();

Also, you need specify default route for your process to make requests to connected WiFi AP permanently. Just add call of next method to your NetworkCallback under onAvaliable like this:

networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        createNetworkRoute(network, connectivityManager);
        }
    };
    if (connectivityManager!= null) connectivityManager.requestNetwork(request, networkCallback);

.

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private static void createNetworkRoute(Network network, ConnectivityManager connectivityManager) {
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
          connectivityManager.bindProcessToNetwork(network);
     } else {
          ConnectivityManager.setProcessDefaultNetwork(network);
     }
 } 

Don't forget disconnect from the bound network:

connectivityManager.unregisterNetworkCallback(networkCallback);

Finally, you can find best practice in different libraries like WifiUtils.

Solution 4

You can try wifisuggestion api, I'm able to connect using them.

final WifiNetworkSuggestion suggestion1 =
            new WifiNetworkSuggestion.Builder()
                    .setSsid("YOUR_SSID")
                    .setWpa2Passphrase("YOUR_PRE_SHARED_KEY")
                    .build();
    final List<WifiNetworkSuggestion> suggestionsList =
            new ArrayList<WifiNetworkSuggestion>();
    suggestionsList.add(suggestion1);

    WifiManager wifiManager =
            (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    int status = wifiManager.addNetworkSuggestions(suggestionsList);
    if (status == 0 ){
        Toast.makeText(this,"PSK network added",Toast.LENGTH_LONG).show();
        Log.i(TAG, "PSK network added: "+status);
    }else {
        Toast.makeText(this,"PSK network not added",Toast.LENGTH_LONG).show();
        Log.i(TAG, "PSK network not added: "+status);
    }

Solution 5

I was also facing the same issue, even after 3 months I was unable to solve this. But I have found one awesome and cool solution.

startActivity(new Intent("android.settings.panel.action.INTERNET_CONNECTIVITY"))

Just add these lines instead of connecting to the wifi from the app, this will prompt user to select a wifi and connect and as soon as user do it, it will connect to the wifi and also it will have internet also.

Just connecting to the wifi from the app will not access the internet. Do this, this is the best solution.

Share:
12,890
NizarETH
Author by

NizarETH

it's me

Updated on June 06, 2022

Comments

  • NizarETH
    NizarETH about 2 years

    I had this function to connect in Wifi network, below Android 10 it works fine, but when I tried on Android 10, I had a successful connection but WITHOUT internet, I knew it's a bug in Android 10 but I found this application which can connect to wifi from Android 10 with no problem. I'm blocked for days.

    My function :

    private void connectToWifi(String ssid, String password)
        {
            WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                try {
                    Log.e(TAG,"connection wifi pre Q");
                    WifiConfiguration wifiConfig = new WifiConfiguration();
                    wifiConfig.SSID = "\"" + ssid + "\"";
                    wifiConfig.preSharedKey = "\"" + password + "\"";
                    int netId = wifiManager.addNetwork(wifiConfig);
                    wifiManager.disconnect();
                    wifiManager.enableNetwork(netId, true);
                    wifiManager.reconnect();
    
                } catch ( Exception e) {
                    e.printStackTrace();
                }
            } else {
                Log.e(TAG,"connection wifi  Q");
    
                WifiNetworkSpecifier wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
                    .setSsid( ssid )
                    .setWpa2Passphrase(password)
                        .build();
    
                NetworkRequest networkRequest = new NetworkRequest.Builder()
                        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                        .setNetworkSpecifier(wifiNetworkSpecifier)
                        .build();
    
                 connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
    
                     networkCallback = new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(Network network) {
                        super.onAvailable(network);
    
                         connectivityManager.bindProcessToNetwork(network);
                        Log.e(TAG,"onAvailable");
                    }
    
                      @Override
                      public void onLosing(@NonNull Network network, int maxMsToLive) {
                          super.onLosing(network, maxMsToLive);
                          Log.e(TAG,"onLosing");
                      }
    
                      @Override
                    public void onLost(Network network) {
                        super.onLost(network);
                        Log.e(TAG, "losing active connection");
                    }
    
                    @Override
                    public void onUnavailable() {
                        super.onUnavailable();
                        Log.e(TAG,"onUnavailable");
                    }
                };
                connectivityManager.requestNetwork(networkRequest,networkCallback);
    
    
            }
        }
    
    • BlackHatSamurai
      BlackHatSamurai almost 4 years
      Are you testing this on a device or emulator?
    • NizarETH
      NizarETH almost 4 years
      I test on a device
    • Rahul Sharma
      Rahul Sharma over 3 years
      @Euphor08 did you found any solution for this?
    • NizarETH
      NizarETH over 3 years
      @RahulSharma compile your app with targetSdkVersion 28, still the best workaround for the moment.
    • Rahul Sharma
      Rahul Sharma over 3 years
      @euphor but that won't work after 2nd Nov deadline. We can't push update to play store after 2nd Nov. Any other workaround?
  • NizarETH
    NizarETH almost 4 years
    no, it's not working, I used this lib before, and I had the same issue, I contacted the owner so, he use it only for IoT, and with internet access limited only inside the app, so for now it's Android bug, hope they will share the fix soon
  • Lex Hobbit
    Lex Hobbit almost 4 years
    @Euphor08 i'am using code that i posted above and its working perfectly on Android Q devices (Pixel 4XL, Moto G7, SG S20).
  • Lex Hobbit
    Lex Hobbit almost 4 years
    @Euphor08 i misunderstood your question. Do you want to connect to WiFi App on Android Q for internet access?
  • NizarETH
    NizarETH almost 4 years
    there's a scope of internet access in Android Q you will have internet only inside your app if you open a browser you loss internet. the question is how to connect to a hotspot with an app to have internet access with no limitation, hope it's clear now, sorry if my question not direct
  • hiburn8
    hiburn8 almost 4 years
    For security reasons, I don't believe this would be possible. If your app could just connect to any hotspot, this would be a huge security issue. If android < 10 let you do this... fair enough... but i wouldn't expect to be able to do this again going forward without a rooted device.
  • Lex Hobbit
    Lex Hobbit almost 4 years
    @Euphor08 maybe you need try to compile your app with targetSdkVersion 28?
  • NizarETH
    NizarETH almost 4 years
    yes, this is what I did but I'm looking for a solution in Android 10. Thank's
  • Karol Żygłowicz
    Karol Żygłowicz over 3 years
    This answear should have more +1s. This is the way to go targetting Android 10
  • Blue Bot
    Blue Bot over 3 years
    Unfortunately not possible since November 2020 - "From 2 November 2020, app updates must target Android 10 (API level 29) or higher" from https://developer.android.com/distribute/best-practices/deve‌​lop/target-sdk
  • Always Learning
    Always Learning almost 3 years
    Just a minor nit, but you don't need .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRI‌​CTED) since that capability is included by default.
  • Brian Reinhold
    Brian Reinhold over 2 years
    I always get onUnavailable() doing the above even though I know the network is available. Any idea why?
  • Brian Reinhold
    Brian Reinhold over 2 years
    You put a lot of work into this I see. When I try this I always get onUnavailable() as I noted in another comment above and the user (me) did nothing. Do I have to disconnect from the currently connected wifi network first before connecting to a new one?
  • LethalMaus
    LethalMaus over 2 years
    Thank you. onUnavailable can be called for a number of reasons such as user cancellation, network not being found and possibly even a bug within the android kernel. To help you narrow it down I would need to see some code
  • LethalMaus
    LethalMaus over 2 years
    Also knowing which devices you test it on helps and make sure the network is 'forgotten' beforehand
  • Brian Reinhold
    Brian Reinhold over 2 years
    Forgot to take the CAPABILITY_INTERNET out
  • LethalMaus
    LethalMaus over 2 years
    Happens, glad its working for you now