I have am having some issues with getting consistent results when checking if the network is available or not.
I use this code snippet inside a class AppPreferences to check the availability of a network.
/**
* @return the networkAvailable
*/
public boolean isNetworkAvailable() {
connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
networkAvailable = connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isConnected();
return networkAvailable;
}
Before each run I set the context as below:
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
appPreferences.setContext(getBaseContext());
if (appPreferences.isNetworkAvailable()){
// perform task
}
}
},
0,
UPDATE_INTERVAL);
I do know it is not tied to the background thread as I have a onReceive call doing the same logic and still this check fails.
It seems to predominantly happen when it moves between a cellular data connection and to wifi, or vice versa. The Context in which it was started seems to stay even though I update it.
Does anyone have any idea what could be the issue here?