Internet listener Android example

31,683

Solution 1

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">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>

And add this permission

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

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 -

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");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            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;
}

Solution 2

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:

private final NetworkStateReceiver stateReceiver = new NetworkStateReceiver();

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    registerReceiver(stateReceiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(stateReceiver);
}

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):

public class NetworkStateReceiver extends BroadcastReceiver {

    private static boolean online = true;  // we expect the app being online when starting

    public static final String TAG = NetworkStateReceiver.class.getSimpleName();

    public void onReceive(Context context, Intent intent) {
        Log.d(TAG,"Network connectivity change");
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = manager.getActiveNetworkInfo();
        if (ni == null || ni.getState() != NetworkInfo.State.CONNECTED) {
            Log.d(TAG,"There's no network connectivity");
            if (online) // don't show the message if already offline
                Toast.makeText(context, R.string.noInternet, Toast.LENGTH_SHORT).show();
            online = false;
        } else {
            Log.d(TAG,"Network "+ni.getTypeName()+" connected");
            if (!online)  // don't show the message if already online
                Toast.makeText(context, R.string.backOnline, Toast.LENGTH_SHORT).show();
            online = true;
        }
    }
}

If starting your app when being offline, the Toast message will appear; otherwise it appears only when losing / re-establishing the connection .

Share:
31,683

Related videos on Youtube

Zeeshan Chaudhry
Author by

Zeeshan Chaudhry

Extreme Programmer

Updated on March 14, 2020

Comments

  • Zeeshan Chaudhry
    Zeeshan Chaudhry about 4 years

    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.

  • helios
    helios over 11 years
  • Zeeshan Chaudhry
    Zeeshan Chaudhry over 11 years
    I have tried this solution but this not working dude. also gives error at super.onReceive(context, intent);
  • Zeeshan Chaudhry
    Zeeshan Chaudhry over 11 years
    cannot directly invoke abstract methord onReceive(context, intent)
  • Chirag
    Chirag over 11 years
    Just Create BroadCast Receiver and write the above code and delcare it in manifest file . nothing else
  • Zeeshan Chaudhry
    Zeeshan Chaudhry over 11 years
    i have created a seperate class NetworkStateReceiver and write the above code there also add the manifest code in manifest .xml file but it gives error at super.onReceive(context, intent);
  • Zeeshan Chaudhry
    Zeeshan Chaudhry over 11 years
    I have rechecked complete code. public class NetworkStateReceiver extends BroadcastReceiver is there any thing i have to do in main activity ?
  • Chirag
    Chirag over 11 years
    No nothing to do in main activity . just declare it in manifest file
  • Zeeshan Chaudhry
    Zeeshan Chaudhry over 11 years
    O yes its done Don't know wats the problem have to restart Emulator to make "F8" Work. Thanks alot @Chirag Raval Stay Blessed buddy
  • raja
    raja almost 11 years
    change super.onReceive(context, intent); to onReceive(context, intent);
  • alicanbatur
    alicanbatur over 10 years
    @ChiragRaval could you just delete the line : super.onReceive(context, intent); please ? All errors is this.
  • Darko Petkovski
    Darko Petkovski almost 10 years
    I've just tested this code and it actually works - about the super.onReceive(context, intent); error - I've just commented out this line and its working like it should! @ChiragRaval Thanks for this helpfull answer!
  • Muhammad Babar
    Muhammad Babar over 9 years
    EXTRA_NETWORK_INFO is deprecated. Here's a workaround stackoverflow.com/a/20590138/1939564
  • CopsOnRoad
    CopsOnRoad about 6 years
    From Android 7.0, you can't really register a BroadcastReceiver statically that can listen for Connectivity change.
  • Kuldeep Bhimte
    Kuldeep Bhimte almost 4 years
    Would this work when the internet is connected and the strength is weakening(not disconnected)
  • pepan
    pepan almost 4 years
    @KuldeepBhimte not really; it only works when an event is triggered; check here: stackoverflow.com/questions/1206891/…
  • Rahul Shyokand
    Rahul Shyokand over 3 years
    Cool, Worked Like a Charm Seems easier than registering Intent in AndroidManifest.xml