I am working on an Android app that will continuously remain connected to Internet. If Internet is dow, it should give an appropriate message to the User.
Is there any thing like Internet Listener? Or how to implement this event that whenever Internet connection is not available it should give alert.
The code from Chirag Raval above certainly works. The trouble is that the listener will get invoked even when the application is not running in foreground.
IMHO, the better approach is to register / unregister the receiver in the
onResume()
/onPause()
methods of all your application activities. This code should do it:Obviously, remove the registration from
AndroidManifest.xml
file.Using this solution, the receiver will be called also when switching between activities of your application (assuming you are closing them). In such a case, use a static flag (being shared between all your activities) like in the example below (called
online
):If starting your app when being offline, the Toast message will appear; otherwise it appears only when losing / re-establishing the connection .
Create one Broadcast Receiver for that and register it in manifest file.
First create a new class
NetworkStateReceiver
and extend BroadcastReceiver.Put this code in your AndroidManifest.xml under the "application" element:
And add this permission
EDIT
This code just detects connectivity change but cannot tell whether the network it is connected to has a internet access. Use this method to check that -