Via Cà Matta 2 - Peschiera Borromeo (MI)
+39 02 00704272
info@synaptica.info

Delphi Android WiFi Manager

Digital solution partner

Delphi Android WiFi Manager

L’obiettivo era quello di connettersi a livello programmatico ad una specifica WiFi da qui è sorta l’esigenza di gestire in modo completo la classe Java WifiManager.

Nei tre metodi principali riportati di seguito avremo:

  1. riconoscimento dell’IP Address assegnato alla porta wifi
  2. Elenco delle Wifi disponibili (quelle che il dispositivo riconosce)
  3. Elenco delle configurazioni WiFi salvate sul dispositivo
  4. Possibilità di connettersi ad una specifica Wifi creandone la configurazione se la stessa non esiste

 



function IntToInetAddr(ipInt : Integer) : String;
var
 b : TBytes;
Begin
    SetLength(b,4);
    b[3] := ((ipInt and $FF000000) shr 24);
    b[2] := ((ipInt and $00FF0000) shr 16);
    b[1] := ((ipInt and $0000FF00) shr 8);
    b[0] := (ipInt and $000000FF);
    result := b[0].ToString() + '.' +
              b[1].ToString() + '.' +
              b[2].ToString() + '.' +
              b[3].ToString();

End;

(*
https://stackoverflow.com/questions/36098871/how-to-search-and-connect-to-a-specific-wifi-network-in-android-programmatically

http://blog.csdn.net/cmdasm/article/details/38357613
*)

procedure TForm4.Button1Click(Sender: TObject);
Var
  networkSSID : String;
  networkPass : String;
  WifiManagerObj: JObject;
  WifiManager: JWifiManager;
  AWifiConfiguration: JList;
  WifiInfo: JWifiInfo;
  WifiConfiguration,WinConf :  JWifiConfiguration;
  networkId: Integer;
  Done: Boolean;
  iter: JIterator;

begin
//  https://geekori.com/details.php?que_id=26676
  WifiManagerObj := SharedActivityContext.getSystemService(TJContext.JavaClass.WIFI_SERVICE);
  WifiManager := TJWifiManager.Wrap((WifiManagerObj as ILocalObject).GetObjectID);
  WifiInfo := WifiManager.getConnectionInfo();

 if CheckBox1.IsChecked then
  Begin
    networkSSID := '"' + edSid.Text + '"';
    networkPass := '"' + edPwd.Text + '"';
  End
 Else
  Begin
    networkSSID := edSid.Text;
    networkPass := edPwd.Text;
  End;

 WifiConfiguration := nil;
 networkId := -1;

 iter := WifiManager.getConfiguredNetworks().iterator;
 while iter.hasNext do
     Begin
       WinConf := TJWifiConfiguration.Wrap((iter.next as ILocalObject).GetObjectID);
       //Memo1.lines.add(WinConf.networkId.ToString + ' --> ' + JStringToString(WinConf.SSID));
       if JStringToString(WinConf.SSID) = networkSSID then
        Begin
         WifiConfiguration := WinConf;
         networkId := WinConf.networkId;
        End;

     End;

 if WifiConfiguration = nil then
  Begin
    Memo1.lines.add('Network not found try to create configuration');
    //WifiConfiguration := TJWifiConfiguration.Create;
    WifiConfiguration := TJWifiConfiguration.JavaClass.init;

    WifiConfiguration.SSID := StringToJString(networkSSID);

    WifiConfiguration.preSharedKey := StringToJString(networkPass);

     WifiConfiguration.hiddenSSID := true;


    WifiConfiguration.allowedAuthAlgorithms.&set(TJWifiConfiguration_AuthAlgorithm.JavaClass.OPEN);
    WifiConfiguration.allowedGroupCiphers.&set(TJWifiConfiguration_GroupCipher.JavaClass.TKIP);
    WifiConfiguration.allowedGroupCiphers.&set(TJWifiConfiguration_GroupCipher.JavaClass.CCMP);
    WifiConfiguration.allowedKeyManagement.&set(TJWifiConfiguration_KeyMgmt.JavaClass.WPA_PSK);
    WifiConfiguration.allowedPairwiseCiphers.&set(TJWifiConfiguration_GroupCipher.JavaClass.TKIP);
    WifiConfiguration.allowedPairwiseCiphers.&set(TJWifiConfiguration_GroupCipher.JavaClass.CCMP);
    WifiConfiguration.status := TJNsdManager.JavaClass.NSD_STATE_ENABLED;

    networkId := WifiManager.addNetwork(WifiConfiguration);
  End;



  if networkId = -1 then
  begin
    Done := False;
    Memo1.lines.add('ERROR: networkId = -1');
  end
  Else
   Memo1.lines.add('networkId = ' + networkId.ToString());

  if WifiManager.disconnect = False then
  begin
    Done := False;
    Memo1.lines.add('ERROR: not disconnected');
  end;


  if done then
   Begin
    AWifiConfiguration := WifiManager.getConfiguredNetworks();
    done := False;
    Memo1.lines.add(' Configured network size: ' +  AWifiConfiguration.size.ToString());
    iter := AWifiConfiguration.iterator;
    while iter.hasNext do
     Begin
       WinConf := TJWifiConfiguration.Wrap((iter.next as ILocalObject).GetObjectID);
       Memo1.lines.add(WinConf.networkId.ToString + ' --> ' + JStringToString(WinConf.SSID));
       if WinConf.networkId = networkId then
         done := WifiManager.enableNetwork(networkId, true)
       Else
         WifiManager.disableNetwork(WinConf.networkId);

     End;


//    done := WifiManager.enableNetwork(networkId, true);

   WifiManager.reconnect;
//    done := WifiManager.enableNetwork(AWifiConfiguration.get(networkId).hashCode, true);
   End;

  if Done then
   Begin
     Memo1.lines.add('Connected');
   End
  Else
   Begin
     Memo1.lines.add('Not Connected to selected network');

   End;

  GetIpAddress;


end;

procedure TForm4.Button2Click(Sender: TObject);
 var
  WifiManagerObj: JObject;
  WifiManager: JWifiManager;
  WifiInfo: JWifiInfo;
begin
  WifiManagerObj := SharedActivityContext.getSystemService(TJContext.JavaClass.WIFI_SERVICE);
  WifiManager := TJWifiManager.Wrap((WifiManagerObj as ILocalObject).GetObjectID);
  WifiInfo := WifiManager.getConnectionInfo();


  Memo1.Lines.Clear;
  Memo1.Lines.Add('Wifi Enabled: ' + WifiManager.isWifiEnabled.ToString);
  Memo1.Lines.Add('Wifi State: ' + WifiManager.getWifiState.ToString);
  Memo1.Lines.Add('Ping Supplicant: ' + WifiManager.pingSupplicant.ToString);


  Memo1.Lines.Add('BSSID: ' + JStringToString(WifiInfo.getBSSID));
  Memo1.Lines.Add('HiddenSSID: ' + WifiInfo.getHiddenSSID.ToString);
  Memo1.Lines.Add('IpAddress: ' + WifiInfo.getIpAddress.ToString);
  Memo1.Lines.Add('LinkSpeed: ' + WifiInfo.getLinkSpeed.ToString + 'Mbps');
  Memo1.Lines.Add('MacAddress: ' + JStringToString(WifiInfo.getMacAddress));
  Memo1.Lines.Add('NetworkId: ' + WifiInfo.getNetworkId.ToString);
  Memo1.Lines.Add('Rssi: ' + WifiInfo.getRssi.ToString + 'dBm');
  Memo1.Lines.Add('SSID: ' + JStringToString(WifiInfo.getSSID));
  Memo1.Lines.Add('SupplicantState: ' + JStringToString(WifiInfo.getSupplicantState.toString));
  GetIpAddress;

end;

procedure TForm4.Button3Click(Sender: TObject);
var
  WifiManagerObj: JObject;
  WifiManager: JWifiManager;
  ScanResult: JScanResult;
  i: Integer;
begin
  WifiManagerObj := SharedActivityContext.getSystemService(TJContext.JavaClass.WIFI_SERVICE);
  WifiManager := TJWifiManager.Wrap((WifiManagerObj as ILocalObject).GetObjectID);

  Memo1.Lines.Clear;

  for i := 0 to WifiManager.getScanResults.size - 1 do
  begin
    ScanResult := TJScanResult.Wrap((WifiManager.getScanResults.get(i) as ILocalObject).GetObjectID);



    memo1.Lines.Add( 'SSID: ' + JStringToString(ScanResult.SSID));
    memo1.Lines.Add( 'frequency: ' + ScanResult.frequency.ToString +
    'MHz' + '  level: ' + ScanResult.level.ToString + 'dBm)');





//    ListBox1.AddObject(ListBoxItem);
  end;

//  ListBox1.EndUpdate;
end;

procedure TForm4.Button4Click(Sender: TObject);
begin

// networkSSID := '"WiTmm3"';
// networkPass := '"simona1987"';
  edSid.Text := 'WiTmm3';
  edPwd.Text := 'simona1987';
end;

procedure TForm4.Button5Click(Sender: TObject);
begin
 Memo1.Lines.Clear;
end;

procedure TForm4.GetIpAddress;
var
  WifiManagerObj: JObject;
  WifiManager: JWifiManager;
  WifiInfo: JWifiInfo;
begin
  label1.text := '127.0.0.1';
  { TODO : Trovare il modo di leggere il corrente ipaddress del dispositivo }
  try
    WifiManagerObj := SharedActivityContext.getSystemService(TJContext.JavaClass.WIFI_SERVICE);
    WifiManager := TJWifiManager.Wrap((WifiManagerObj as ILocalObject).GetObjectID);
    WifiInfo := WifiManager.getConnectionInfo;
    label1.text := IntToInetAddr(WifiInfo.getIpAddress);
    if label1.text = '0.0.0.0' then
      label1.text := '127.0.0.1';
  except
    on e: exception do
    begin
      label1.text := '127.0.0.1';
      raise Exception.Create(e.Message);
    end;
  end;
end;

procedure TForm4.FormCreate(Sender: TObject);
Begin
  GetIpAddress;
End;