Zeeshan Chaudhry Zeeshan Chaudhry - 1 year ago 94
Java Question

Internet listener Android example

I am working on Android app that will continuously remains connected with Internet. If Internet is down that it should give appropriate message to User.

Is there any thing like Internet Listener? or how to Implement this Event that when ever Internet connection is not available it should give alert.

Answer Source

Create one Broadcast Receiver for that and register it in manifest file.

First create a new class NetworkStateReceiver and extend BroadcastReceiver.

public class NetworkStateReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
     Log.d("app","Network connectivity change");
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            Log.i("app","Network "+ni.getTypeName()+" connected");
     if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
            Log.d("app","There's no network connectivity");

Put this code in your AndroidManifest.xml under the "application" element:

<receiver android:name=".NetworkStateReceiver">
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

And add this permission

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


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 -

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
    } else {
    Log.d(LOG_TAG, "No network available!");
    return false;