0

As title states I wanted to ask, how can I keep checking if the device has internet connection? I use the following class:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class checkConnection {

    private static checkConnection instance = new checkConnection();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static checkConnection getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected = networkInfo != null && networkInfo.isAvailable() &&
                networkInfo.isConnected();

        return connected;


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }
}

But this only checks once the activity starts if the device has or not internet connection, if I wanted to keep checking how can I create a loop throughout the activity?

Paul Ratazzi
  • 6,289
  • 3
  • 38
  • 50
LS_
  • 6,763
  • 9
  • 52
  • 88

3 Answers3

2
public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

 if(checkInternet(context))
 {
   Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); 
 }

}


boolean checkInternet(Context context) {
        ServiceManager serviceManager = new ServiceManager(context);
        if (serviceManager.isNetworkAvailable()) {
            return true;
        } else {
            return false;
        }
    }

}

ServiceManager.java

public class ServiceManager extends ContextWrapper {

public ServiceManager(Context base) {
    super(base);
}

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

}

permissions :

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.INTERNET" />

And don't forget to register the receiver like this in main activity -

registerReceiver(mConnReceiver, 
           new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
   }
}

ref. here

Community
  • 1
  • 1
Darpan
  • 5,623
  • 3
  • 48
  • 80
1

You have to use Brodcast Receiver to register a listner whenever connectivity change and then check internet connection like this.

    public class NetworkConnectivityListener {
     private static final String TAG = "NetworkConnectivityListener";
     private static final boolean DBG = true;

     private Context mContext;
     private State mState;
     private boolean mListening;
     private String mReason;
     private boolean mIsFailover;
     boolean isWifiConnected = false;
     boolean isMobileConnected = false;
     private static NetworkConnectivityListener Networkobject;
     private MainThreadBus mThreadBus;
     public static NetworkConnectivityListener newInstance() {
      if (Networkobject == null) {
       Networkobject = new NetworkConnectivityListener();
      }
      return Networkobject;
     }

     /** Network connectivity information */
     private NetworkInfo mNetworkInfo;

     /**
      * In case of a Disconnect, the connectivity manager may have already
      * established, or may be attempting to establish, connectivity with another
      * network. If so, {@code mOtherNetworkInfo} will be non-null.
      */
     private NetworkInfo mOtherNetworkInfo;

     private ConnectivityBroadcastReceiver mReceiver;

     private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
      @SuppressWarnings("deprecation")
      @Override
      public void onReceive(Context context, Intent intent) {
       String action = intent.getAction();

       if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
         || mListening == false) {
        Log.d(TAG, "onReceived() called with " + mState.toString()
          + " and " + intent);
        return;
       }

       ConnectivityManager connMgr = (ConnectivityManager) context
         .getSystemService(Context.CONNECTIVITY_SERVICE);

       NetworkInfo networkInfo = connMgr
         .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

       if (networkInfo != null)
        isWifiConnected = networkInfo.isConnected();

       networkInfo = connMgr
         .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

       if (networkInfo != null)
        isMobileConnected = networkInfo.isConnected();

       Log.d("network status", "wifi == " + isWifiConnected
         + " and mobile == " + isMobileConnected);

       boolean noConnectivity = intent.getBooleanExtra(
         ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

       if (noConnectivity) {
        mState = State.NOT_CONNECTED;
       } else {
        mState = State.CONNECTED;
       }

       mNetworkInfo = (NetworkInfo) intent
         .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
       mOtherNetworkInfo = (NetworkInfo) intent
         .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

       mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
       mIsFailover = intent.getBooleanExtra(
         ConnectivityManager.EXTRA_IS_FAILOVER, false);
       System.out.println("Printing the MYTest" + mNetworkInfo);
       if (DBG) {
        Log.d(TAG,
          "onReceive(): mNetworkInfo="
            + mNetworkInfo
            + " mOtherNetworkInfo = "
            + (mOtherNetworkInfo == null ? "[none]"
              : mOtherNetworkInfo + " noConn="
                + noConnectivity) + " mState="
            + mState.toString());
       }

       mThreadBus.post(getState());
      }
     };

     public enum State {
      UNKNOWN,

      /** This state is returned if there is connectivity to any network **/
      CONNECTED,
      /**
       * This state is returned if there is no connectivity to any network.
       * This is set to true under two circumstances:
       * <ul>
       * <li>When connectivity is lost to one network, and there is no other
       * available network to attempt to switch to.</li>
       * <li>When connectivity is lost to one network, and the attempt to
       * switch to another network fails.</li>
       */
      NOT_CONNECTED
     }

     /**
      * Create a new NetworkConnectivityListener.
      */
     public NetworkConnectivityListener() {
      mState = State.UNKNOWN;
      mReceiver = new ConnectivityBroadcastReceiver();
     }

     /**
      * This method starts listening for network connectivity state changes.
      * 
      * @param context
      */
     public synchronized void startListening(Context context,Bus bus) {
      if (!mListening) {
       mContext = context;
       mThreadBus=new MainThreadBus(bus);
       IntentFilter filter = new IntentFilter();
       filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
       context.registerReceiver(mReceiver, filter);
       mListening = true;

      }
     }

     /**
      * This method stops this class from listening for network changes.
      */
     public synchronized void stopListening() {
      if (mListening) {
       mContext.unregisterReceiver(mReceiver);
       mContext = null;
       mNetworkInfo = null;
       mOtherNetworkInfo = null;
       mIsFailover = false;
       mReason = null;
       mThreadBus=null;
       mListening = false;
      }
     }

     public State getState() {
      return mState;
     }

     /**
      * Return the NetworkInfo associated with the most recent connectivity
      * event.
      * 
      * @return {@code NetworkInfo} for the network that had the most recent
      *         connectivity event.
      */
     public NetworkInfo getNetworkInfo() {
      return mNetworkInfo;
     }

     /**
      * If the most recent connectivity event was a DISCONNECT, return any
      * information supplied in the broadcast about an alternate network that
      * might be available. If this returns a non-null value, then another
      * broadcast should follow shortly indicating whether connection to the
      * other network succeeded.
      * 
      * @return NetworkInfo
      */
     public NetworkInfo getOtherNetworkInfo() {
      return mOtherNetworkInfo;
     }

     /**
      * Returns true if the most recent event was for an attempt to switch over
      * to a new network following loss of connectivity on another network.
      * 
      * @return {@code true} if this was a failover attempt, {@code false}
      *         otherwise.
      */
     public boolean isFailover() {
      return mIsFailover;
     }

     /**
      * An optional reason for the connectivity state change may have been
      * supplied. This returns it.
      * 
      * @return the reason for the state change, if available, or {@code null}
      *         otherwise.
      */
     public String getReason() {
      return mReason;
     }

     public boolean iswifiConnected() {
      return isWifiConnected;
     }

     public boolean ismobileConnected() {
      return isMobileConnected;
     }

     public class MainThreadBus extends Bus {
      private final Bus mBus;
      private final Handler mHandler = new Handler(Looper.getMainLooper());

      public MainThreadBus(final Bus bus) {
       if (bus == null) {
        throw new NullPointerException("bus must not be null");
       }
       mBus = bus;
      }

      @Override
      public void post(final Object event) {
       System.out.println("Printing the Value of Send" + event);
       if (Looper.myLooper() == Looper.getMainLooper()) {
        mBus.post(event);
       } else {
        mHandler.post(new Runnable() {
         @Override
         public void run() {
          mBus.post(event);
         }
        });
       }
      }
     }
    }

I have use otto here but you can use listener.

GovindRathod
  • 867
  • 1
  • 8
  • 22
amit kumar
  • 291
  • 1
  • 6
1

Alternatively you can use TinyBus open source project, which makes you code as simple as this.

public class MyActivity extends Activity {

    private Bus mBus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBus = TinyBus.from(this).wire(new ConnectivityEvents());
        ...
    }

    @Override
    protected void onStart() {
        super.onStart();
        mBus.register(this);
    }

    @Override
    protected void onStop() {
        mBus.unregister(this);
        super.onStop();
    }

    @Subscribe
    public void onConnectivityEvent(ConnectionChangedEvent event) {
        if (event.isConnected()) {
            // connected

        } else {
            // disconnected

        }
    }

    ...
}
sergej shafarenka
  • 20,071
  • 7
  • 67
  • 86