Search code examples
androidandroid-internet

How to check Internet access at realtime?


I found a lot of topics how to check the Internet access. But I cannot understand how to make it dynamically. For example, I send a request (it will work in a some another thread) and device loses the Internet connection. How I can cancel my request on this event?


Solution

  • Here's something I cooked earlier; maybe it will help:

        public class NetworkStateMonitor extends BroadcastReceiver {
            Context mContext;
            boolean mIsUp;
    
            public interface Listener {
                void onNetworkStateChange(boolean up);
            }
    
            public NetworkStateMonitor(Context context) {
                mContext = context;
                //mListener = (Listener)context;
                IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
                context.registerReceiver(this, intentFilter);
                mIsUp = isUp();
            }
    
            /**
            * call this when finished with it, and no later than onStop(): callback will crash if app has been destroyed
            */
            public void unregister() {  
                mContext.unregisterReceiver(this);
            }
    
            /*
            * can be called at any time
            */
            public boolean isUp() {
                ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                return activeNetworkInfo!=null && activeNetworkInfo.isConnectedOrConnecting();
            }
    
            /**
            * registerReceiver callback, passed to mListener
            */
            @Override public void onReceive(Context context, Intent intent) {       
                boolean upNow = isUp();
                if (upNow == mIsUp) return;     // no change
                mIsUp = upNow;
                ((Listener)mContext).onNetworkStateChange(mIsUp);
            }
        }