Isn't it often the way that when solving a problem you suspect a complex cause and it turns out to be something quite basic!
As an RF Engineer by profession, it should have been obvious that with the RPI having just a single RF transceiver to support both WiFi and AP connections, the channel number of both connections would have to remain the same at all times to achieve my objective.
While at boot-up I set the RPi AP to channel 2, when the RPi connects via WiFi, the transceiver will switch to the channel assigned by the AP to which the RPi connects. This may be any channel number and the RPi will accordingly switch to the same channel, say 9 in my test case.
My external device will connect to the RPi using that channel, and I can successfully identify WiFi networks available to the RPi and switch to the desired network via the code in
post #10 by specifying the index of the appropriate network entry in wpa_supplicant.conf.
Note that
@Chris2's code in
post #2 shows how to write a wpa_supplicant.conf file.
However, when the RPi connects to the new WiFi network, its transceiver will change to the channel number of that network, which is unlikely to be the original channel number. For instance in my test case it is channel 1. And of course the AP channel now becomes that new channel number, with the now obvious consequential effect of dropping the connection with the device previously connected to perform the configuration setup. Of course it can be reconnected, but I don't like that inconvenience for the user.
So given with the B4X community's help I've been able to connect to a WiFi network via code as per the thread title, I'll mark this thread as SOLVED, but unfortunately my proposed arrangement of configuring WiFi networks via the AP connection won't work as desired with the RPi. I will either have to accept the need to reconnect to the AP after a WiFi network switch, add a WiFi dongle to the RPi to be able to provide two separate channels or I am thinking of exploring use of a Bluetooth connection over which to do the configuration.