Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

There is no real connection to the SSID on the Android phone #356

Open
Jay-57blocks opened this issue Nov 10, 2023 · 0 comments
Open

There is no real connection to the SSID on the Android phone #356

Jay-57blocks opened this issue Nov 10, 2023 · 0 comments

Comments

@Jay-57blocks
Copy link

Jay-57blocks commented Nov 10, 2023

wifi_iot: ^0.3.18+1

It should be noted that the WIFI SSID I want to connect to does not have the ability to access the Internet. I only use it to exchange data with applications.

Calling [WiFiForIoTPlugin.connect] returns true. At this time, the WIFl list has shown that it is connected to the SSID, but the connection is not actually successful because I called './get-bud-serial', which showed a connection error and could not obtain the device serial number.

final connected = await WiFiForIoTPlugin.connect(ssid);

I tried to change a plug-in (plugin_wifi_connect). I only modified this line of code. It worked successfully and obtained the device serial number, but this plug-in is no longer maintained...:

final connected = await PluginWifiConnect.connect(ssid);

This problem is very strange. I don’t know what causes it. I have provided two plug-in [connect] methods. It would be great if this problem can be fixed.

Looking forward to receiving your reply

Plugin 1: PluginWifiConnectPlugin.kt

import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSpecifier

override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    when (call.method) {
      "connect" -> {
        val ssid = call.argument<String>("ssid")
        ssid?.let {
          when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
              val specifier = WifiNetworkSpecifier.Builder()
                      .setSsid(it)
                      .build()
              connect(specifier, result)
              return
            }
            else -> {
              val wifiConfig = createWifiConfig(it)
              connect(wifiConfig, result)
              return
            }
          }
        }
        return
      }
      else -> result.notImplemented()
    }
  }


@SuppressLint("MissingPermission")
  fun connect(@NonNull wifiConfiguration: WifiConfiguration, @NonNull result: Result){
    val network = wifiManager.addNetwork(wifiConfiguration)
    if (network == -1) {
      result.success(false)
      return
    }
    wifiManager.saveConfiguration()

    val wifiChangeReceiver = object : BroadcastReceiver() {
      var count = 0
      override fun onReceive(context: Context, intent: Intent) {
        count++;
        val info = intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO)
        if(info != null && info.isConnected) {
          if (info.extraInfo == wifiConfiguration.SSID || getSSID() == wifiConfiguration.SSID) {
            result.success(true)
            context?.unregisterReceiver(this)
          } else if (count > 1) {
            // Ignore first callback if not success. It may be for the already connected SSID
            result.success(false)
            context?.unregisterReceiver(this)
          }
        }
      }
    }

    val intentFilter = IntentFilter()
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
    context?.registerReceiver(wifiChangeReceiver, intentFilter)

    // enable the new network and attempt to connect to it 
    wifiManager.enableNetwork(network, true)
    networkId = network
  }

Plugin 2: WifiIotPlugin.java

import android.net.MacAddress;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.ScanResult;
import android.net.wifi.SoftApConfiguration;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.net.wifi.WifiNetworkSuggestion;

/// Method to connect to WIFI Network
  private void connectTo(
      final Result poResult,
      final String ssid,
      final String bssid,
      final String password,
      final String security,
      final Boolean joinOnce,
      final Boolean withInternet,
      final Boolean isHidden,
      final Integer timeoutInSeconds) {
    final Handler handler = new Handler(Looper.getMainLooper());
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
      final boolean connected =
          connectToDeprecated(ssid, bssid, password, security, joinOnce, isHidden);
      handler.post(
          new Runnable() {
            @Override
            public void run() {
              poResult.success(connected);
            }
          });
    } else {
      // error if WEP security, since not supported
      if (security != null && security.toUpperCase().equals("WEP")) {
        handler.post(
            new Runnable() {
              @Override
              public void run() {
                poResult.error(
                    "Error", "WEP is not supported for Android SDK " + Build.VERSION.SDK_INT, "");
              }
            });
        return;
      }

      if (withInternet != null && withInternet) {
        // create network suggestion
        final WifiNetworkSuggestion.Builder builder = new WifiNetworkSuggestion.Builder();
        // set ssid
        builder.setSsid(ssid);
        builder.setIsHiddenSsid(isHidden != null ? isHidden : false);
        if (bssid != null) {
          final MacAddress macAddress = macAddressFromBssid(bssid);
          if (macAddress == null) {
            handler.post(
                new Runnable() {
                  @Override
                  public void run() {
                    poResult.error("Error", "Invalid BSSID representation", "");
                  }
                });
            return;
          }
          builder.setBssid(macAddress);
        }

        // set password
        if (security != null && security.toUpperCase().equals("WPA")) {
          builder.setWpa2Passphrase(password);
        }

        // remove suggestions if already existing
        if (networkSuggestions != null) {
          moWiFi.removeNetworkSuggestions(networkSuggestions);
        }

        //builder.setIsAppInteractionRequired(true);
        final WifiNetworkSuggestion suggestion = builder.build();

        networkSuggestions = new ArrayList<>();
        networkSuggestions.add(suggestion);
        if (joinOnce != null && joinOnce) {
          suggestionsToBeRemovedOnExit.add(suggestion);
        }

        final int status = moWiFi.addNetworkSuggestions(networkSuggestions);
        Log.e(WifiIotPlugin.class.getSimpleName(), "status: " + status);

        handler.post(
            new Runnable() {
              @Override
              public void run() {
                poResult.success(status == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS);
              }
            });
      } else {
        // Make new network specifier
        final WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
        // set ssid
        builder.setSsid(ssid);
        builder.setIsHiddenSsid(isHidden != null ? isHidden : false);
        if (bssid != null) {
          final MacAddress macAddress = macAddressFromBssid(bssid);
          if (macAddress == null) {
            handler.post(
                new Runnable() {
                  @Override
                  public void run() {
                    poResult.error("Error", "Invalid BSSID representation", "");
                  }
                });
            return;
          }
          builder.setBssid(macAddress);
        }

        // set security
        if (security != null && security.toUpperCase().equals("WPA")) {
          builder.setWpa2Passphrase(password);
        }

        final NetworkRequest networkRequest =
            new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .setNetworkSpecifier(builder.build())
                .build();

        final ConnectivityManager connectivityManager =
            (ConnectivityManager) moContext.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (networkCallback != null) connectivityManager.unregisterNetworkCallback(networkCallback);

        networkCallback =
            new ConnectivityManager.NetworkCallback() {
              boolean resultSent = false;

              @Override
              public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                if (!resultSent) {
                  joinedNetwork = network;
                  poResult.success(true);
                  resultSent = true;
                }
              }

              @Override
              public void onUnavailable() {
                super.onUnavailable();
                if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
                  connectivityManager.unregisterNetworkCallback(this);
                }
                if (!resultSent) {
                  poResult.success(false);
                  resultSent = true;
                }
              }

              @Override
              public void onLost(Network network) {
                super.onLost(network);
                if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
                  connectivityManager.unregisterNetworkCallback(this);
                }
              }
            };

        connectivityManager.requestNetwork(
            networkRequest, networkCallback, handler, timeoutInSeconds * 1000);
      }
    }
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant