Search code examples
androiddelphifiremonkeyandroid-wifi

How to programmatically enable wi-fi on android device in Delphi?


I was need to enable and disable programmatically wi-fi on my Android device in Delphi.


Solution

  • This sample can solve this issue:

    procedure TForm1.btWiFiEnableClick(Sender: TObject);
    var
      WiFIServiceNative: JWifiManager;
    begin
      // https://developer.android.com/reference/android/net/wifi/WifiManager.html#getWifiState()
      // https://developer.android.com/reference/android/net/wifi/WifiManager.html#WIFI_STATE_DISABLED
      WiFIServiceNative := TJWifiManager.Wrap(TAndroidHelper.Context.getSystemService(TJContext.JavaClass.WIFI_SERVICE));
      if Assigned(WiFIServiceNative) then begin
        Memo1.Lines.Add('Has Wifi manager');
        Memo1.Lines.Add('Wifi state is ' + IntToStr(WiFIServiceNative.getWifiState));
    
        // if WiFIServiceNative.getWifiState = TJWifiManager.JavaClass.WIFI_STATE_DISABLED then
        if WiFIServiceNative.getWifiState < 2 then // WIFI_STATE_DISABLING or WIFI_STATE_DISABLED
        begin
          Memo1.Lines.Add('Try to Wi-Fi on:');
          if WiFIServiceNative.setWifiEnabled(true) then
            Memo1.Lines.Add(' - ' + IntToStr(TJWifiManager.JavaClass.WIFI_STATE_ENABLED) + ' OK')
          else
            Memo1.Lines.Add(' - FAIL');
        end else begin
          Memo1.Lines.Add('Try to Wi-Fi off:');
          if WiFIServiceNative.setWifiEnabled(false) then
            Memo1.Lines.Add(' - ' + IntToStr(TJWifiManager.JavaClass.WIFI_STATE_DISABLED) + ' OK')
          else
            Memo1.Lines.Add(' - FAIL');
        end;
      end;
    end;
    

    It needs to use the following permissions:

    android:name="android.permission.ACCESS_WIFI_STATE"
    android:name="android.permission.WRITE_SETTINGS"