Skip to content Skip to sidebar Skip to footer

Android Connection With Esp8266 On One Plus ( Android 6.0.1)

Retrofit on Android 6.0 has a problem making Http calls after connecting to Access Point Steps to reproduce: Connect to Esp8266 Access Point Make an http call to http://192.168.4

Solution 1:

Problem

Error ENONET means that NetworkInfo.isConnected() returns false

Indicates whether network connectivity exists and it is possible to establish connections and pass data. Always call this before attempting to perform data transactions.

Solution

Spawn a daemon Thread which waits for the Wifi network (given by ssid) to "fully" connect (see above) and call your callback with either true (successfully connected) or false (timeout or error).

Implementation

privateConnectivityManagerconnectivity= ...;
privateWifiManagerwifi= ...;

privatevoidwaitForWifi(final String ssid, final Consumer<Boolean> callback) {
    finalThreadthread=newThread(() -> {
        for (inti=0; i < 300; i++) {
            finalWifiInfoinfo= wifi.getConnectionInfo();
            NetworkInfonetworkInfo=null;

            for (final Network network : connectivity.getAllNetworks()) {
                finalNetworkCapabilitiescapabilities= connectivity.getNetworkCapabilities(network);

                if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                    networkInfo = connectivity.getNetworkInfo(network);
                    break;
                }
            }

            if (info != null && info.ssid == ssid && networkInfo != null && networkInfo.isConnected()) {
                callback.accept(true);
                return;
            }

            Thread.sleep(100);
        }

        callback.accept(false);
    });

    thread.setDaemon(true);
    thread.start();
}

Notes

  • ssid must be enclosed in double quotation marks (see wifiConfiguration.SSID)
  • ConnectivityManager.getAllNetworks() requires permission ACCESS_NETWORK_STATE
  • WifiManager.getConnectionInfo() requires permissions ACCESS_NETWORK_STATE and ACCESS_COARSE_LOCATION (runtime permission)

Post a Comment for "Android Connection With Esp8266 On One Plus ( Android 6.0.1)"