I'd like to know if there's a mechanism so whenever I try to use internet, somehow AUTOMATICALLY behind the scences this method (isNetworkAvailable) will be called.
The question is NOT about how to check for internet connection as I already know that:
public boolean isNetworkAvailable(){
ConnectivityManager cm =
(ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
To clarify myself, I want to prevent from calling isNetworkAvailable() each time I use internet connection (either by my classes which I call explicitly or by third party classes I use that opens internet connections by themselves), so my code won't be filled everywhere with:
if(isNetworkAvailable()){
// send message to server or open some other internet connection
}
But this function somehow will be called before each attempt to connect internet.
Hope I've cleared myself. Couldn't find a solution on SO.
P.S. My app CAN run on offline mode, so I don't want a simple broadcast reciever that blocks the app whenever there's no internet connection (like some apps do).
I have used BroadCastReceiver, which will check my Internet connectivity automatically.
NetworkUtil.java
NetworkConnectivityCheck.java
After these two files, just initialise the class before onCreate Method , it will look like this.
MainActivity.java