0
votes
 package com.example.wifiscanner;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.telecom.Connection;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    private WifiManager wifiManager;
    private ListView listView;
    private Button button;
    private int size = 0;
    private List<ScanResult> results;
    private ArrayList<String> arrayList = new ArrayList<>();
    private ArrayAdapter arrayAdapter;
    private String ssid = "SLT-FIBRE";
    private String password = "VMEKF27*";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanWifi();
            }
        });

        listView = findViewById(R.id.listview);
        wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);

        if (!wifiManager.isWifiEnabled()) {

            Toast.makeText(this, "Wifi is disabled", Toast.LENGTH_SHORT).show();
            wifiManager.setWifiEnabled(true);

        }

        arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(arrayAdapter);

        ConnectToNetworkWPA(ssid,password);
        scanWifi();


    }

    public void startScan() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                scanWifi();
            }
        }, 5 * 1000);
    }


    @AfterPermissionGranted(123)
    public void scanWifi() {

        String[] perm = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE};

        if (EasyPermissions.hasPermissions(this, perm)) {

            arrayList.clear();
            registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
            boolean scanStarted = wifiManager.startScan();

            if (scanStarted) {
                Toast.makeText(this, "Scanning true", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Scanning false", Toast.LENGTH_SHORT).show();
            }

            Toast.makeText(this, "PERMISSIONS HAVE BEEN GRANTED", Toast.LENGTH_SHORT).show();


        } else {

            EasyPermissions.requestPermissions(this, "WE REQUIRE THESE PERMISSIONS FOR THE APP TO FUNCTION", 123, perm);
        }

    }


    BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            results = wifiManager.getScanResults();

            unregisterReceiver(this);

            for (ScanResult scanResult : results) {
                arrayList.add(" " + scanResult.SSID + "   " + scanResult.frequency + "    " + scanResult.level + "   " + scanResult.BSSID);
                arrayAdapter.notifyDataSetChanged();


            }

        }

    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        scanWifi();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }

    }

    public void ConnectToNetworkWPA(String SSID, String password) {
        try {
            WifiConfiguration conf = new WifiConfiguration();
            conf.SSID = "\"" + SSID + "\"";   // Please note the quotes. String should contain SSID in quotes

            conf.preSharedKey = "\"" + password + "\"";

            conf.status = WifiConfiguration.Status.ENABLED;
            conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);


            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            int networkId = wifiManager.addNetwork(conf);

            Log.d("connecting", conf.SSID + " " + conf.preSharedKey);
            Log.d("after connecting", conf.SSID + " " + conf.preSharedKey);


            wifiManager.disconnect();
            wifiManager.enableNetwork(networkId, true);
            wifiManager.reconnect();
            Log.d("re connecting", SSID + " " + conf.preSharedKey);

            final NetworkRequest requestForWifi =
                    new NetworkRequest.Builder()
                            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                            .build();

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

            final ConnectivityManager.NetworkCallback  networkCallbackWifi = new ConnectivityManager.NetworkCallback(){

                @Override
                public void onAvailable(@NonNull Network network) {

                    
                }

                @Override
                public void onLost(@NonNull Network network) {

                    
                }
            };

            connectivityManager.requestNetwork(requestForWifi, networkCallbackWifi);



        } catch (Exception ex) {
            ex.getMessage();
            ex.printStackTrace();


        }
    }

    public void BroadCast() {

        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }

        WifiConfiguration netConfig = new WifiConfiguration();

        netConfig.SSID = "HM3355";
        netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

        try {
            Method setWifiApMethod = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            boolean apstatus = (Boolean) setWifiApMethod.invoke(wifiManager, netConfig, true);

            Method isWifiApEnabledmethod = wifiManager.getClass().getMethod("isWifiApEnabled");
            while (!(Boolean) isWifiApEnabledmethod.invoke(wifiManager)) {
            }
            ;
            Method getWifiApStateMethod = wifiManager.getClass().getMethod("getWifiApState");
            int apstate = (Integer) getWifiApStateMethod.invoke(wifiManager);
            Method getWifiApConfigurationMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
            netConfig = (WifiConfiguration) getWifiApConfigurationMethod.invoke(wifiManager);
            Log.e("CLIENT", "\nSSID:" + netConfig.SSID + "\nPassword:" + netConfig.preSharedKey + "\n");

        } catch (Exception e) {

            Log.e(this.getClass().toString(), "", e);

        }

    }
}

         

I am trying to programmatically connect my android app to my esp32 wifi chip but it does not work. Code compiles and runs without a problem but it does not connect to the specified network. No error is shown, even when I debug I see the ssid and password correctly going through the methods but cannot understand why it will no connect to the esp32 , my PC can connect when I use these credentials.

1

1 Answers

0
votes

What you have currently will set up the credentials and connection for a Wi-Fi network but if there are no outstanding requests for that network, the Networking portion of Android will tear it down (or never bring it up).

If you want to also bring up a Wi-Fi network, you need to both setup the credentials as you have currently and request Wi-Fi like so:

final NetworkRequest requestForWifi =
  new NetworkRequest.Builder()
  .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
  .build();

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

final NetworkCallback networkCallbackWifi = new NetworkCallback() {
  @Override
  void onAvailable(Network network) {
      // Once this callback triggers, you've connected to Wi-Fi
      Toast.makeText(context, "CONNECTED TO TRD", Toast.LENGTH_SHORT).show();
  }

  @Override
  void onLost(Network network) {
      // Triggers when this network is lost.
      Toast.makeText(context, "NOT CONNECTED TO TRD", Toast.LENGTH_SHORT).show();
  }
};

connectivityManager.requestNetwork(requestForWifi, networkCallbackWifi);

Finally, change this method signature to be void like so and remove any logic you had around the previous boolean return value:

public void ConnectToNetworkWPA(String networkSSID, String password)

You won't know that you are connected until the networkCallbackWifi#onAvailable callback triggers therefore having the other method return true/false was incorrect.