Is this the right way to detect connection to a WiFi network?
I'm making an application for Android that needs to react to when the device gets connected to a WiFi network, I'm currently trying to implement it using a BroadcastReceiver to monitor android.net.ConnectivityManager.CONNECTIVITY_ACTION - is this way correct, or is there a way that would be more appropriat开发者_StackOverflowe?
@Jase, You need to register to receive WifiManager.NETWORK_STATE_CHANGED_ACTION
. The intent has a NetworkInfo
extra. Examine it to find its state. If the state is NetworkInfo.State.CONNECTED
, then you are connected to a network.
For sample code on achieving this, look here.
Take a look at WifiManager.WIFI_STATE_CHANGED_ACTION
Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown. One extra provides this state as an int. Another extra provides the previous state, if available.
and WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION
Broadcast intent action indicating that a connection to the supplicant has been established (and it is now possible to perform Wi-Fi operations) or the connection to the supplicant has been lost. One extra provides the connection state as a boolean, where true means CONNECTED.
Read from the broadcast or do a check when you get any of them like:
WifiManager wifi=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int state=wifi.getWifiState();
Now you can check state, it will be one of
- WIFI_STATE_DISABLED
- WIFI_STATE_DISABLING
- WIFI_STATE_ENABLED <-- With this you can send/receive data
- WIFI_STATE_ENABLING
- WIFI_STATE_UNKNOWN
精彩评论