Intent action for network events in android sdk
Here's a working example:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><receiver android:name=".receiver.ConnectivityReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter></receiver>
.
public class ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d(ConnectivityReceiver.class.getSimpleName(), "action: " + intent.getAction()); }}
yanchenko's answer is very much useful, i am just simplifying a little bit to get connection status, please modify onReceive as below :
public class ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d(ConnectivityReceiver.class.getSimpleName(), "action: " + intent.getAction()); MyConstants.IS_NETWORK_AVAILABLE = haveNetworkConnection(context); //IS_NETWORK_AVAILABLE this variable in your activities to check networkavailability. } private boolean haveNetworkConnection(Context context) { boolean haveConnectedWifi = false; boolean haveConnectedMobile = false; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] netInfo = cm.getAllNetworkInfo(); for (NetworkInfo ni : netInfo) { if (ni.getTypeName().equalsIgnoreCase("WIFI")) if (ni.isConnected()) haveConnectedWifi = true; if (ni.getTypeName().equalsIgnoreCase("MOBILE")) if (ni.isConnected()) haveConnectedMobile = true; } return haveConnectedWifi || haveConnectedMobile; }}