This question already has an answer here:
I want to check the internet connectivity in each activity. If it is lost a message should be displayed.
Can any one guide me how to achieve this?
This question already has an answer here:
I want to check the internet connectivity in each activity. If it is lost a message should be displayed.
Can any one guide me how to achieve this?
You can do this, for various types of network status
You can check network coverage and data availability of Mobile and wi-fi directly with
For Network coverage availability,
For Data availability if network available
Register a broadcast receiver to handle CONNECTIVITY_ACTION. See this full example. You should update a static variable 'connectionAvailable' that will be accessible everywhere and everytime through its respective getter.
Remember to declare the broadcast receiver in the manifest file:
On the matter of 'checking in each activity', may be you would be interested in using a BaseActivity extended by your activities and managing the test of connectivity and displaying the message.
Also, note that using events (not polling from activities) will be more efficient.
You are not using
ConnectivityManager.getNetworkInfo(0).getState()
andConnectivityManager.getNetworkInfo(1).getState()
properly, instead of hardcoding the values (1) and (0) useConnectivityManager.TYPE_WIFI
andConnectivityManager.TYPE_MOBILE
Correction
should be
Only one connection can be active at any one point. So a simpler answer is:
It also caters for any new type of network such as ConnectivityManager#TYPE_WIMAX
Also make sure that you have the required permission to monitor the network state. You need to add this permission to your AndroidManifest.xml: