When the connection to the Internet is changed, the onReceive method works 2 times (One response is required).
public class NetworkChangeReceiver extends BroadcastReceiver { boolean connection; @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifi != null && wifi.isConnectedOrConnecting()) || (mobile != null && mobile.isConnectedOrConnecting())){ connection = true; } if (connection) { Log.d("Network Available ", "YES"); } else { Log.d("Network Available ", "NO"); } } }
The result in the log when you turn off:
D/Network Available: NO D/Network Available: NO Accordingly, when you turn on:
D/Network Available: YES `D/Network Available: YES