Reputation: 199
I'm trying to make an app, and I'm having some problems I can't solve for now:
My application has to connect to an specific AP with specified name and show the IP gateway. What I am trying to do is that when the app starts, it checks if the WiFi module is enabled. If it's not, then enable it and connect to the AP. If it's enabled, check if it's already connected to the correct AP, and if it's not, connect there.
So, for now I did:
Enable wifi part. It's a function called via AlertDialog named enableWifi() (How to enable/disable WiFi from an application?)
Setup WiFi network information and connect there. It's also a function called via AlertDialog named setupWiFi() (How and what to set to Android WifiConfiguration.preSharedKey to connect to the WPA2 PSK WiFi network)
Get the IP Gateway. It's a function named setIP(). This writes de IP in EditText view. (Programmatically getting the gateway and subnet mask details)
There are two ways of connecting to the AP:
1) Enable Wifi -> Connect to AP
2) Connect to AP
So here comes the problem: When I enable WiFi module, I should wait to finish enabling for starting to connect to the AP, and then wait to finish connection to retrieve the gateway IP. I don't know how to do those "wait" parts. What my app does now if I'm in 2) is connect to AP and get the gateway of the current network, which is still the old one and the one we don't want.
I tried threads such as AsyncTask and Thread but couldn't make it work...
Thanks for reading and I hope this is easy to solve!
Kind regards, Raúl Suárez
Upvotes: 0
Views: 1281
Reputation: 1709
You can listen to the action (ConnectivityManager.CONNECTIVITY_ACTION) and identify if you have connected to an active network or not.
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Additionally you can check the network Type that is currently active(Type_WIFI, Type_MOBILE). Implement a broadcast receiver with this intent filter and do your task in the onReceive() method of the receiver.
Upvotes: 2