Force connect to wifi

edited January 2018 in Android Mode

Hi everyone, I would like to know if its possible to force connect the phone to a pre defined network using any existing wifi libraries? I made a small app that sends accelerometer data to the server through udp but works only if both devices are connected to the same network, on the app side I would like to pre define a network that application automatically connects. Thanks for your help already and Happy New Year! :)

Answers

  • Answer ✓

    @poYo===

    • imports:

                  import android.content.Context;
                  import android.net.wifi.WifiManager;
                  import android.net.wifi.WifiConfiguration;
      
              import android.net.wifi.WifiInfo;
      
              import android.net.wifi.WifiConfiguration.KeyMgmt;
      

    Not sure to understand exactly what you want... Yet it seems to me that, after having added permissions (internet, wifi state, wifi change), verified that wifi is enabled and opened one connexion from your phone to your network you can:

    • create an instance of WifiManager;

    • create an instance of WifiConfiguration;

    • add to it your password and the name of the network using android.net.wifi.WifiConfiguration.KeyMgmt;

    • list all enregistered networks and create a loop for the list; your network will be listed among others.

    • connect to this one that has the name you have choosen (before doing that disconnect from the others)

  • The idea is, I have an Installation, a game that uses the phone as a controller. I don't want the participant to look for the network and connect to it manually. If I can solve it on the application side, that would make the things easier for me. So the final goal would be, the participant downloads the app from the store, click's connect and the app automatically finds the predefined network and connects. I made a simple version while ago that sends the accelerometer and screen activity to the server. But it was just a prototype.

  • edited January 2018

    So that would be something like this?

    import android.content.Context;
    import android.net.wifi.WifiManager;
    import android.net.wifi.WifiConfiguration;
    import android.net.wifi.WifiInfo;
    import android.net.wifi.WifiConfiguration.KeyMgmt;
    
    class wifiConnect {
    
      String WIFI_SSID = "wifi_name";
      String WIFI_PASS = "wifi_pass";
      boolean WIFI_HIDDEN  = false;
    
    
      wifiConfiguration.SSID = String.format("\"%s\"", WIFI_SSID);
      wifiConfiguration.preSharedKey = String.format("\"%s\"", WIFI_PASS);
      wifiConfiguration.hiddenSSID = WIFI_HIDDEN;
    
      wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
      wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
      wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
      wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
      wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
      wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
      wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
      wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
      wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    
    
      void connectToWifi() {
        try {
          Thread.sleep(2000);
        } 
        catch (InterruptedException e) {
          e.printStackTrace();
        }
        publishProgress("Connecting to Wifi Network ....");
        try {
          Thread.sleep(2000);
        } 
        catch (InterruptedException e) {
          e.printStackTrace();
        }
        WifiConfiguration wifiConfiguration = new WifiConfiguration();
        setValuesForWifiConfiguration(wifiConfiguration);
        String message = enableAndConnectWifi(wifiConfiguration);
        publishProgress(message);
        try {
          Thread.sleep(2000);
        } 
        catch (InterruptedException e) {
          e.printStackTrace();
        }
    
        void enableAndConnectWifi() {
    
          String message;
          WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
          wifiManager.addNetwork(wifiConfiguration);
    
          List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
          for ( WifiConfiguration i : list ) {
            if (i.SSID != null && i.SSID.equals("\"" + WIFI_SSID + "\"")) {
              wifiManager.disconnect();
              wifiManager.enableNetwork(i.networkId, true);
              wifiManager.reconnect();
              message = "Network " + WIFI_SSID + " Found";
              return message;
            }
          }
    
          message = "Network " + WIFI_SSID + "Not Found";
          return message;
        }
      }
    
  • @poyo==

    yes, something like that; as soon as possible i ll give a look; as for now what i can say is that i have coded this kind of things with P5...Don't dispair!

  • edited January 2018 Answer ✓

    @Poyo===

    more precisely, code snippet:

        import android.net.Uri;//that is only to verify we are connected
        import android.content.IntentFilter;
        import android.content.BroadcastReceiver;//here i dont use it but in some cases i could be useful
        import android.content.Intent;// used for verifying
    
        import java.util.List;// could be any ArrayList
        import android.content.Context;
        import android.net.wifi.WifiManager;
        import android.net.wifi.WifiConfiguration;
    
        import android.net.wifi.WifiInfo;
        import android.net.wifi.ScanResult;//not used here but if you want to know all wifi spots detected
        import android.net.wifi.WifiConfiguration.KeyMgmt;
        import android.app.Activity;
    
        Activity act;
        Context context;
        Intent inten;
        WifiManager wm;
        //List<ScanResult> results;
        int size = 0;
        WifiInfo wifiInfo ;
    
        int MIN_RSSI        = -100;// not used here, useful if you want to test the signal quality
            int MAX_RSSI        = -55;  //the same
            int levels          = 101;//the same
    
        int niveau = 0;//the same
    
    
        void setup(){
    
          size(displayWidth, displayHeight);
           act = this.getActivity();
          context = act.getApplicationContext();
    
          wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    
        //wifiInfo= wm.getConnectionInfo();
        //String Name = wifiInfo.getSSID();
    
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + "here the name" + "\""; 
        conf.wepKeys[0] = "\"" + "here the pass" + "\""; 
        conf.preSharedKey = "\""+ "here the pass" +"\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
        wm.addNetwork(conf);
    
        List<WifiConfiguration> list = wm.getConfiguredNetworks();
        for( WifiConfiguration i : list ) {
          println(i.SSID);
            if(i.SSID != null && i.SSID.equals("\"" + "here the name" + "\"")) {
        //here i only adapt your code
    
              println("je me deconnecte");
                 wm.disconnect();
                 wm.enableNetwork(i.networkId, true);
                 wm.reconnect();  
                 println("je me reconnecte"+i.SSID);
    
                 break;
            }           
         }
        //wm.startScan();
        lanceWeb("https://www.google.fr/");
        }
    
    
        void draw(){
    
    
        }
    
        public void lanceWeb( String url ) {
            Intent browse = new Intent( Intent.ACTION_VIEW , Uri.parse( url ) );
    
            act.startActivity( browse );
        }
    
  • But this only connects if the network is known or ? I simplified the code a bit to test and on console it was listing the known networks. What if I want it to connect to a network which is not know for the device?

    here is the code that I edited.

    import java.util.List;// could be any ArrayList
    import android.content.Context;
    import android.net.wifi.WifiManager;
    import android.net.wifi.WifiConfiguration;
    
    import android.net.wifi.WifiInfo;
    import android.net.wifi.WifiConfiguration.KeyMgmt;
    import android.app.Activity;
    
    Activity act;
    Context context;
    WifiManager wm;
    //List<ScanResult> results;
    int size = 0;
    WifiInfo wifiInfo ;
    
    
    
    void setup() {
    
      size(displayWidth, displayHeight);
      act = this.getActivity();
      context = act.getApplicationContext();
    
      wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    
      //wifiInfo= wm.getConnectionInfo();
      //String Name = wifiInfo.getSSID();
    
      WifiConfiguration conf = new WifiConfiguration();
      conf.SSID = "\"" + "Deltafi" + "\""; 
      conf.wepKeys[0] = "\"" + "lipa4138" + "\""; 
      conf.preSharedKey = "\""+ "lipa4138" +"\"";
      conf.wepTxKeyIndex = 0;
      conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
      conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
      wm.addNetwork(conf);
    }
    
    
    
    void draw() {
      textSize(height/18);
      textMode(CENTER);
      fill(255);
      text("hello world",width/2,height/2);
    
      if (mousePressed == true){
      List<WifiConfiguration> list = wm.getConfiguredNetworks();
      for ( WifiConfiguration i : list ) {
        println(i.SSID);
        if (i.SSID != null && i.SSID.equals("\"" + "Deltafi" + "\"")) {
          //here i only adapt your code
    
          println("je me deconnecte");
          wm.disconnect();
          wm.enableNetwork(i.networkId, true);
          wm.reconnect();  
          println("je me reconnecte"+i.SSID);
    
          break;
        }
      }
      }
    }
    
  • Or is it because of some permission mistake I made?

  • Answer ✓

    @poyo===

    yes: this is the code you have given:: i adapted it to ¨P5, that s all!!!- now , if you want to connect to any networks found (scan result!!!) try that....

  • edited January 2018

    Now I get the error "The Global Variable "networkId" does not exist" :S

        import java.util.List;
    import android.content.Context;
    import android.net.wifi.WifiManager;
    import android.net.wifi.WifiConfiguration;
    import android.net.wifi.ScanResult;
    import android.net.wifi.WifiInfo;
    import android.net.wifi.WifiConfiguration.KeyMgmt;
    import android.app.Activity;
    
    Activity act;
    Context context;
    WifiManager wm;
    List<ScanResult> results;
    WifiInfo wifiInfo ;
    String networkSSID = "Deltafi";
    String networkPass = "lipa4138";
    
    
    void setup() {
    
      size(displayWidth, displayHeight, P2D);
      act = this.getActivity();
      context = act.getApplicationContext();
    }
    
    
    
    void draw() {
      textSize(height/18);
      textMode(CENTER);
      fill(255);
      text("hello world", width/2, height/2);
    
      if (mousePressed == true) {
        wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration conf = new WifiConfiguration();
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        conf.preSharedKey = "\""+ networkPass +"\"";
        WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); 
        wifiManager.addNetwork(conf);
        List<ScanResult> result = wifiManager.getScanResults();
        for ( ScanResult i : result ) {
          if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
            println("Disconnectting from all networks");
            wifiManager.disconnect();
            println("Connecting to " + networkSSID);
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();               
    
            break;
          }
        }
      }
    }
    
  • edited January 2018

    @PoYo===

    normal: scan does not know nothing about networkID; netWorkID is known when you list configured networks...So= you have firstly to scan and get a list of wifi spots, registred or not registered; then you create a new configuration for the network you want to use, add it to the registered list and finally use the first code i have given there.

  • I'll start bashing my head :D

    So I tried some stuff but now I get an error that I don't understand at all...

    FATAL EXCEPTION: GLThread 337489
    Process: processing.test.wifi_list, PID: 30539
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
        at processing.test.wifi_list.WiFi_List$WiFiList.connect(WiFi_List.java:160)
        at processing.test.wifi_list.WiFi_List.draw(WiFi_List.java:84)
        at processing.core.PApplet.handleDraw(Unknown Source)
        at processing.opengl.PSurfaceGLES$RendererGLES.onDrawFrame(Unknown Source)
        at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1548)
        at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1259)
    

    new code :

    import java.util.List;
    import android.content.Context;
    import android.content.BroadcastReceiver;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.net.wifi.ScanResult;
    import android.net.wifi.WifiManager;
    import android.app.Activity;
    import android.net.wifi.WifiConfiguration.KeyMgmt;
    import android.net.wifi.WifiConfiguration;
    
    
    WiFiList wifiList;
    ArrayList<WiFiListItem> wifiNetworks;
    int fontSize;
    String message = "Tap to scan";
    
    void setup() {
      size(displayWidth, displayHeight, P2D);
      orientation(PORTRAIT);
    
      wifiList = new WiFiList();
      wifiList.init();
      wifiNetworks = wifiList.getItems();
    
      fontSize = height/30;
      textSize(fontSize);
      textAlign(LEFT, TOP);
      noStroke();
    }
    
    
    void draw() {
      background(255);  
    
      fill(0);
      text(message, width/2, height/2);
    
      int currentHeight = 3 * fontSize;
      int barHeight = 5 + fontSize;
    
      // draw a bar representing the signal strengths for each network
      for (WiFiListItem item : wifiNetworks) {
        fill(200);
        float barWidth = map(item.level, -100, -10, 30, width);
        rect(0, currentHeight, barWidth, barHeight);
        fill(0);
        text(item.name + " : " + item.level, 10, currentHeight);
        currentHeight += barHeight;
      }
      // start scanning when the screen is tapped
      if (mousePressed == true) {
    
        wifiList.scan();
        wifiList.connect();
      }
    }
    
    // this function is called when the WiFiList object is done scanning
    void wifiScanFinished() {
      message = "Scan Finished";
      wifiNetworks = wifiList.getItems();
    }
    

    WiFiList class

    class WiFiList {
      protected WifiManager wifiManager;
      protected List<ScanResult> scanList;
      protected ArrayList<WiFiListItem> items;
      protected boolean bScanning = false;
      protected Activity act;
      protected Context context;
    
      WiFiList() {
        items = new ArrayList<WiFiListItem>();
      }
    
      boolean isScanning() {
        return bScanning;
      }
    
      ArrayList<WiFiListItem> getItems() {
        while (bScanning) {
        }
        return new ArrayList<WiFiListItem>(items);
      }
    
      void init() {
        wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);
    
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    
        getActivity().registerReceiver(new BroadcastReceiver() {
          public void onReceive(Context context, Intent intent) {
            println("WiFiList: scan finished");
            scanList = wifiManager.getScanResults();
            for (ScanResult networkDevice : scanList) {
              updateItem(networkDevice.SSID, networkDevice.level);
            }
            bScanning = false;
            wifiScanFinished();
          }
        }
        , filter);
      }
    
      void updateItem(String name, int level) {
        for (WiFiListItem item : items) {
          if (item.name.equals(name)) {
            item.level = level;
            println("[Updated] " + name + " : " + level);
            return;
          }
        }
        items.add(new WiFiListItem(name, level));
        println("[Added] " + name + " : " + level);
      }
    
      void scan() {
        if (bScanning) {
          println("WiFiList: already scanning");
          return;
        }
        bScanning = true;
        println("WiFiList: starting scan");
        wifiManager.startScan();
      }
    
      void connect() {
    
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + "Deltafi" + "\""; 
        conf.wepKeys[0] = "\"" + "lipa4138" + "\""; 
        conf.preSharedKey = "\""+ "lipa4138" +"\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
        wifiManager.addNetwork(conf);
    
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for ( WifiConfiguration i : list ) {
          println(i.SSID);
          if (i.SSID != null && i.SSID.equals("\"" + "Deltafi" + "\"")) {
            //here i only adapt your code
    
            println("Disconnecting from all networks");
            wifiManager.disconnect();
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();  
            println("connecting to "+i.SSID);
    
            break;
          }
        }
      }
    }
    
    class WiFiListItem {
      String name;
      int level;
    
      WiFiListItem(String name, int level) {
        this.name = name;
        this.level = level;
      }
    }
    
  • @Poyo===

    of course: you never initialize your context! && BTW: unregister your receiver because without that it will run undefinitely...

  • on line 67 wifi list class I had a silly mistake, tnx for pointing out but I didn't understand the unregistering receiver part also now the app doesn't give error but still doesn't connect to unknown network

  • @PoYo===

    i ll give a look at that but i am quite sure that your scan is never completed because your receiver is never unregistered and so on connect cannot run!

  • Any luck ? cuz I am still stuck in same point :D starting to hate this :D

  • edited January 2018

    @PoYo===

    try this=== BroadcastReceiver monRecepteur;

         monRecepteur = new BroadcastReceiver() {
            @ Override
            public void onReceive(Context context, Intent intent) {
             scanList = wifiManager.getScanResults();
                for (ScanResult networkDevice : scanList) {
                  println(networkDevice.SSID);
                  updateItem(networkDevice.SSID, networkDevice.level);
                }
                 bScanning = false;
                wifiScanFinished();
                getActivity().unregisterReceiver(monRecepteur);
           monRecepteur = null;
            }
          };
             getActivity().registerReceiver(monRecepteur, filter);
    

    then unregister also in onPause() &&& onStop() &&& onDestroy() (adding a condtion: if(monRecepteur !=null){}

  • gives an error - Cannot refer to the non-final local variable monRecepteur defined in an enclosing scope -

    can you somehow implement it to the code and send that way? I know its too much to ask but I am already super confused with every single change :D

  • edited January 2018

    Cannot refer to the non-final local variable monRecepteur defined in an enclosing scope.

    Judging by the fact there's no datatype before monRecepteur where it's being initialized, much probably it has been declared someplace else. L-)

    So there's a real chance monRecepteur is a field, rather than a local variable, which has been declared, but not initialized yet, at the top of the sketch. :\">

    However, Java surprisingly can accept local variables or parameters to be accessed inside classes and lambdas created inside a function/method, as long as they're declared as final too. <:-P

    Or since Java 8, that also works if they can be determined as effectively final, even though not explicitly declared as such. :ar!

    For those who also know JS, accessing variables defined in an enclosing outer function from within enclosed inner functions is called closure. B-)

  • edited January 2018

    Tnx GoToLoop, fixed the error cuz I realized I was registering the monRecepteur in inner scope, yet still doesn't connect to the network :D

    when tapped, scans the networks, prints them on the screen than registers the pre defined network in the configured networks but doesn't connect to it.

  • edited January 2018

    current code

    import java.util.List;
    import android.content.Context;
    import android.content.BroadcastReceiver;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.net.wifi.ScanResult;
    import android.net.wifi.WifiManager;
    import android.app.Activity;
    import android.net.wifi.WifiConfiguration.KeyMgmt;
    import android.net.wifi.WifiConfiguration;
    
    
    WiFiList wifiList;
    ArrayList<WiFiListItem> wifiNetworks;
    int fontSize;
    String message = "Tap to scan";
    boolean connect = false;
    
    void setup() {
      size(displayWidth, displayHeight, P2D);
      orientation(PORTRAIT);
    
      wifiList = new WiFiList();
      wifiList.init();
      wifiNetworks = wifiList.getItems();
    
      fontSize = height/30;
      textSize(fontSize);
      textAlign(LEFT, TOP);
      noStroke();
    }
    
    
    void draw() {
      background(255);  
    
      fill(0);
      text(message, width/2, height/2);
    
      int currentHeight = 3 * fontSize;
      int barHeight = 5 + fontSize;
    
      // draw a bar representing the signal strengths for each network
      for (WiFiListItem item : wifiNetworks) {
        fill(200);
        float barWidth = map(item.level, -100, -10, 30, width);
        rect(0, currentHeight, barWidth, barHeight);
        fill(0);
        text(item.name + " : " + item.level, 10, currentHeight);
        currentHeight += barHeight;
      }
      // start scanning when the screen is tapped
      if (mousePressed == true) {
        wifiList.scan();
      }
      if (mousePressed == true && message == "Scan Finished") {
        wifiList.connect();
      }
    }
    
    // this function is called when the WiFiList object is done scanning
    void wifiScanFinished() {
      message = "Scan Finished";
      wifiNetworks = wifiList.getItems();
    }
    
    
    class WiFiList {
      protected WifiManager wifiManager;
      protected List<ScanResult> scanList;
      protected ArrayList<WiFiListItem> items;
      protected boolean bScanning = false;
      protected Activity act;
      protected Context context;
      protected BroadcastReceiver monRecepteur;
      WiFiList() {
        items = new ArrayList<WiFiListItem>();
      }
    
      boolean isScanning() {
        return bScanning;
      }
    
      ArrayList<WiFiListItem> getItems() {
        while (bScanning) {
        }
        return new ArrayList<WiFiListItem>(items);
      }
    
      void init() {
        wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);
    
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    
    
        monRecepteur = new BroadcastReceiver() {
          @ Override
            public void onReceive(Context context, Intent intent) {
            scanList = wifiManager.getScanResults();
            for (ScanResult networkDevice : scanList) {
              println(networkDevice.SSID);
              updateItem(networkDevice.SSID, networkDevice.level);
            }
            bScanning = false;
            wifiScanFinished();
            getActivity().unregisterReceiver(monRecepteur);
            monRecepteur = null;
          }
        };
        getActivity().registerReceiver(monRecepteur, filter);
      }
    
      void updateItem(String name, int level) {
        for (WiFiListItem item : items) {
          if (item.name.equals(name)) {
            item.level = level;
            println("[Updated] " + name + " : " + level);
            return;
          }
        }
        items.add(new WiFiListItem(name, level));
        println("[Added] " + name + " : " + level);
      }
    
      void scan() {
        if (bScanning) {
          println("WiFiList: already scanning");
          return;
        }
        bScanning = true;
        println("WiFiList: starting scan");
        wifiManager.startScan();
      }
    
      void connect() {
    
        wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);
    
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + "test" + "\""; 
        conf.wepKeys[0] = "\"" + "testtest" + "\""; 
        conf.preSharedKey = "\""+ "testtest" +"\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
        wifiManager.addNetwork(conf);
    
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for ( WifiConfiguration i : list ) {
          println(i.SSID);
          if (i.SSID != null && i.SSID.equals("\"" + "test" + "\"")) {
            //here i only adapt your code
    
            println("Disconnecting from all networks");
            wifiManager.disconnect();
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();  
            println("connecting to "+i.SSID);
    
            break;
          }
        }
      }
    }
    
    class WiFiListItem {
      String name;
      int level;
    
      WiFiListItem(String name, int level) {
        this.name = name;
        this.level = level;
      }
    }
    
  • @PoYo=== of course you have to declare monRecepteur as a global, instance of BroadcastReceiver...

  • well even so still doesn't work :D

  • edited January 2018

    @PoYo===

    put your "new" code; what does not work???what error???

  • Error still remains the same, scans the network, lists them yet doesn't connect. I am using WPA/WPA2 security.

    import java.util.List;
    import android.content.Context;
    import android.content.BroadcastReceiver;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.net.wifi.ScanResult;
    import android.net.wifi.WifiManager;
    import android.app.Activity;
    import android.net.wifi.WifiConfiguration.KeyMgmt;
    import android.net.wifi.WifiConfiguration;
    
    
    WiFiList wifiList;
    ArrayList<WiFiListItem> wifiNetworks;
    int fontSize;
    String message = "Tap to scan";
    boolean connect = false;
    
    void setup() {
      size(displayWidth, displayHeight, P2D);
      orientation(PORTRAIT);
    
      wifiList = new WiFiList();
      wifiList.init();
      wifiNetworks = wifiList.getItems();
    
      fontSize = height/30;
      textSize(fontSize);
      textAlign(LEFT, TOP);
      noStroke();
    }
    
    
    void draw() {
      background(255);  
    
      fill(0);
      text(message, width/2, height/2);
    
      int currentHeight = 3 * fontSize;
      int barHeight = 5 + fontSize;
    
      // draw a bar representing the signal strengths for each network
      for (WiFiListItem item : wifiNetworks) {
        fill(200);
        float barWidth = map(item.level, -100, -10, 30, width);
        rect(0, currentHeight, barWidth, barHeight);
        fill(0);
        text(item.name + " : " + item.level, 10, currentHeight);
        currentHeight += barHeight;
      }
      // start scanning when the screen is tapped
      if (mousePressed == true) {
        wifiList.scan();
        wifiList.connect();
      }
    
    }
    
    // this function is called when the WiFiList object is done scanning
    void wifiScanFinished() {
      message = "Scan Finished";
      wifiNetworks = wifiList.getItems();
      println("message is " + message );
    }
    
         class WiFiList {
      protected WifiManager wifiManager;
      protected List<ScanResult> scanList;
      protected ArrayList<WiFiListItem> items;
      protected boolean bScanning = false;
      protected Activity act;
      protected Context context;
      protected BroadcastReceiver monRecepteur;
      String networkSSID = "test";
      String networkPASS = "testtest";
    
      WiFiList() {
        items = new ArrayList<WiFiListItem>();
      }
    
      boolean isScanning() {
        return bScanning;
      }
    
      ArrayList<WiFiListItem> getItems() {
        while (bScanning) {
        }
        return new ArrayList<WiFiListItem>(items);
      }
    
      void init() {
        wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);
    
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    
    
        monRecepteur = new BroadcastReceiver() {
          @ Override
            public void onReceive(Context context, Intent intent) {
            scanList = wifiManager.getScanResults();
            for (ScanResult networkDevice : scanList) {
              println(networkDevice.SSID);
              updateItem(networkDevice.SSID, networkDevice.level);
            }
            bScanning = false;
            wifiScanFinished();
            getActivity().unregisterReceiver(monRecepteur);
            monRecepteur = null;
          }
        };
        getActivity().registerReceiver(monRecepteur, filter);
      }
    
      void updateItem(String name, int level) {
        for (WiFiListItem item : items) {
          if (item.name.equals(name)) {
            item.level = level;
            println("[Updated] " + name + " : " + level);
            return;
          }
        }
        items.add(new WiFiListItem(name, level));
        println("[Added] " + name + " : " + level);
      }
    
      void scan() {
        if (bScanning) {
          println("WiFiList: already scanning");
          return;
        }
        bScanning = true;
        println("WiFiList: starting scan");
        wifiManager.startScan();
      }
    
      void connect() {
    
        wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);
    
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\""; 
        conf.wepKeys[0] = "\"" + networkPASS + "\""; 
        conf.preSharedKey = "\""+ networkPASS +"\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 
        wifiManager.addNetwork(conf);
    
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for ( WifiConfiguration i : list ) {
          println(i.SSID);
          if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
    
            println("Disconnecting from all networks");
            wifiManager.disconnect();
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();  
            println("connecting to "+i.SSID);
    
            break;
          }
        }
      }
    }
    
    class WiFiListItem {
      String name;
      int level;
    
      WiFiListItem(String name, int level) {
        this.name = name;
        this.level = level;
      }
    }
    
Sign In or Register to comment.