title: How can I receive a notification when the device loses network connectivity?
body: <p>I know you can write code through which you can determine whether the device is connected to a network.</p>
  
  <p>But in my app what I want to do is get a notification if the device changes its state from 'network' to 'no network'. This would happen, for example, when the user travels into a tunnel and loses signal, etc. Or when on WiFi, the user goes out of range of the access point and no longer has access to the internet.</p>
  
  <p>Does the Android API provide something where you can register a listener so that you get notified every time there is a change in network state?</p>
  
  <p>I found this code and tried to use it, but it does not do anything. I don't get any notifications when the network state changes.</p>
  
  <pre><code>public class ConnectivityManager extends PhoneStateListener{
  
  Activity activity;
  public ConnectivityManager(Activity a){
      TelephonyManager telephonyManager = (TelephonyManager)a.getSystemService(Context.TELEPHONY_SERVICE);
      telephonyManager.listen(this, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
      activity = a;
  }
  
  @Override
  public void onDataConnectionStateChanged(int state) {
      super.onDataConnectionStateChanged(state);
      switch (state) {
      case TelephonyManager.DATA_DISCONNECTED:
          new AlertDialog.Builder(activity).
          setCancelable(false).
          setTitle("Connection Manager").
          setMessage("There is no network connection. Please connect to internet and start again.").
          setNeutralButton("Ok", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                  System.exit(0);
              }
          }).create();
          break;
  
      case TelephonyManager.DATA_CONNECTED:
          break;
      }
  }
  }
  </code></pre>
  
  <p>Also, I have added the appropriate permissions in AndroidManifest.xml:</p>
  
  <pre><code>&lt;uses-permission android:name="android.permission.INTERNET"&gt;&lt;/uses-permission&gt;
  &lt;uses-permission android:name="android.permission.READ_PHONE_STATE"&gt;&lt;/uses-permission&gt;
  &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"&gt;&lt;/uses-permission&gt;
  </code></pre>