Skip to content

Instantly share code, notes, and snippets.

@neilbantoc
Created August 25, 2014 17:08
Show Gist options
  • Save neilbantoc/db7aa9547cf423ce706f to your computer and use it in GitHub Desktop.
Save neilbantoc/db7aa9547cf423ce706f to your computer and use it in GitHub Desktop.
Code snippet for getting notified when getting connected/disconnected from the network
/*
* Don't forget to add these to the manifest!
* <receiver
* android:name="ConnectivityReceiver"
* android:enabled="true"
* android:label="ConnectivityActionReceiver" >
* <intent-filter>
* <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
* </intent-filter>
* </receiver>
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
*/
public class ConnectivityReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
Log.e("ConnectivityReceiver", "Network is disconnected");
// broadcast disconnected
} else {
Log.e("ConnectivityReceiver", "Network is connected");
// broadcast connected
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment