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?
ServiceManager.java
permissions :
And don't forget to register the receiver like this in main activity -
ref. here
You have to use Brodcast Receiver to register a listner whenever connectivity change and then check internet connection like this.