I am new to Android development. How can I set up a listener for WiFi connections/disconnections inside an Activity? It has to be inside of the Activity because I have UART connection set up in it and need to send the WiFi status information to UART Device. I have tried some things with BroadcastReceivers but failed. Here is my last try:
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
if(networkInfo.isConnected()){
Log.d("WIFI", "CONNECTED");
}else{
Log.d("WIFI", "DISCONNECTED");
}
}
}};
I may also need some help on how to register the BroadcastReceiver, currently I'm doing this inside of the Activity's onResume
:
this.registerReceiver(this.myWifiReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
And in onPause
:
this.unregisterReceiver(myWifiReceiver);
EDIT:
Thanks to Devunwired's answer I've achieved what I wanted, I'm posting the code for future reference.
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
SupplicantState newState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
switch(newState){
case ASSOCIATED:
Log.d("WIFI", "CONNECTED");
break;
case DISCONNECTED:
if(!disconnected){
Log.d("WIFI", "DISCONNECTED");
disconnected = true;
}
}
}};
I also moved the BroadcastReceiver
registration to onStart
(and consequently moved the unregistration to onStop
), because onResume
wasn't always called:
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
Depending on what you mean by "connections/disconnections" you might not be observing the correct broadcast action. ConnectivityManager.CONNECTIVITY_ACTION
triggers when a default connection is fully established or lost.
You might be more interested in WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION
or WifiManager.SUPPLICANT_STATE_CHANGED_ACTION
, which trigger as the association state of the WiFi radio changes.
I have tried some things with BroadcastReceivers but failed
If the above actions don't satisfy your needs, I would encourage you to elaborate on the failures you are experiencing.