I have this BroadcastReceiver implementation in my Fragment :
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
//do stuff
}
//Other actions implementation
}
}
};
With standart register/unregister methods:
@Override
public void onStart() {
super.onStart();
getActivity().registerReceiver(receiver, getIntentFilter());
}
@Override
public void onStop() {
super.onStop();
getActivity().unregisterReceiver(receiver);
}
And receiver with same implementation for WifiManager.NETWORK_STATE_CHANGED_ACTION in other Fragment
The issue: this action triggers everytime one of the fragments started, but i need it to trigger only if Wifi was really just connected, and as the name of action says WifiManager.NETWORK_STATE_CHANGED_ACTION, so it should work only if Wifi state changes
Edit: as was replied this action will trigger every time by the default, so my question is: There is no action for Wifi connecting ?
That's how the WifiManager works when you register for NETWORK_STATE_CHANGED_ACTION. When you register it, you will get 1 update immediately, to show the current state.
To circumvent this, you could have a simple boolean in your fragment set as default to 'true'. In your broadcast receiver, check if this is true, and if so, it's the first time you get an update, set it to false and then simply ignore the update. The next time it's called, the boolean will be true and you can use the data.
private boolean firstTime = true;
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(firstTime) {
firstTime = false;
return;
}
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
//do stuff
}
//Other actions implementation
}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With