I am having a strange issue. I have a very simple piece of code that is meant to trigger whenever someone connects to a wifi access point.
IntentFilter ConnectedFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
getApplicationContext().registerReceiver(ConnectedToAPReceiver, ConnectedFilter);
private BroadcastReceiver ConnectedToAPReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
final String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
{
ConnectivityManager connManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo Wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (Wifi.isConnected())
{
// If we get here, it means that the user has just connected to wifi.
}
}
}
};
This code works very well for what I need it to do. However I am getting strange occurrence, that when the back, or home button is pressed the broadcast receiver is also triggered. Also, loading up the App triggers this as well.
Does anyone know why pressing these buttons would be viewed by Android as causing a connectivity change? And does anyone have any idea's how to easily distinguish between these button presses and a valid connectivity change.
This is part of a solution thanks to some work.
Firstly I have two classes, an activity class and a service class. In my activity class, I set a variable in the service class using a broadcast receiver whenever the onPause and the onDestroy are called. (These get triggered when the user presses these buttons). The receiver in the service class picks up this intent and sets the public variable.
Then in the activity classes onResume I check this variable, and send another intent to the service to reset the variable to it's default state. Here I also set a local flag. When I'm doing any processing I simply check that flag beforehand and handle it appropriately.