How To Use Supplicant_state_changed_action Wifi Broadcastreceiver - Android
I want to show the connection process on the screen when my device is connecting to the wifi network. SUPPLICANT_STATE_CHANGED_ACTION is provided by WifiManager but i don't know ho
Solution 1:
You can indeed use the broadcasted intents for SUPPLICANT_STATE_CHANGED_ACTION:
The app needs the permission in its Manifest file:
<uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE" />Then register for the system broadcast:
MyWifiStateReceiverhandler=newMyWifiStateReceiver();
context.registerReceiver(handler, newIntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
the registerReceiver() needs an instance of a class implementing BroadcastReceiver as its first argument. In that code you can act on the Wifi state changes by overriding the onReceive method. For example
publicclassMyWifiStateReceiverextendsBroadcastReceiver
{
@OverridepublicvoidonReceive(Context context, Intent intent)
{
if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION))
{
SupplicantStatestate= (SupplicantState) intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
switch(state)
{
case COMPLETED:
case DISCONNECTED:
...
}
}
}
}
For the possible Wifi state values, see http://developer.android.com/reference/android/net/wifi/SupplicantState.html
Solution 2:
I don't know of a callback method that lets you know when the wifi status has changed. I polled the information using a Handler running in the background.
Add the handler to your class.
privateWifiStatusHandlerwifiStatusHandler=newWifiStatusHandler();
Start it by calling
wifiStatusHandler.start();
The code I used is below.
/**
* Checks for wifi status updates.
*/privateclassWifiStatusHandlerextendsHandler {
privatebooleanrunning=false;
publicvoidhandleMessage(Message message) {
if (running) {
//check wifi status hereWifiManagerwifiMgr= (WifiManager) getSystemService(Context.WIFI_SERVICE);
intcurWifiState= wifiMgr.getWifiState();
SupplicantStateinfo= wifiMgr.getConnectionInfo().getSupplicantState();
WifiInfocurWifi= wifiMgr.getConnectionInfo();
Log.i(TAG,"WIFI STATE = " + info.toString());
//update the TextView etc.
sleep();
}
}
privatevoidsleep() {
removeMessages(0);
sendMessageDelayed(obtainMessage(0), REFRESH_DELAY);
}
publicsynchronizedvoidstart() {
running = true;
removeMessages(0);
sendMessageDelayed(obtainMessage(0), 0);
}
publicsynchronizedvoidstop() {
running = false;
}
}
Post a Comment for "How To Use Supplicant_state_changed_action Wifi Broadcastreceiver - Android"