Here's what you can use wherever you want but remember it should be started at least once which means either put this in an onCreate
or if in a method then call the method at least once.
Handler handler = new Handler();
int timeDelay = 5000; //5 seconds
handler.postDelayed(new Runnable(){
public void run(){
if(!isOnline)
{
yourMethodCall();
}
handler.postDelayed(this, timeDelay );
}
}, delay);
public boolean isOnline() throws InterruptedException, IOException {
String command = "ping -c 1 google.com";
return (Runtime.getRuntime().exec(command).waitFor() == 0);
}
This is the code which will check for WORKING internet connection for every 5 seconds and if the connection is not working then it will call your method in it. Also, notice that Handler code is to be placed in a method and isOnline() is a method.
Working here is highlighted because the most common way to check for internet connection actually return true if a WiFi is connected without internet (basically a hotspot with no internet). But as you just want to check for no connection, you can use this code too.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
But if using this way, you'll have to declare a permission in AndroidManifest.XML which is <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Use this, it will work great.
And Yes, it will run in the background. Not a problem in my app but some users reported that isOnline()
method which is using ping to check connection can sometimes freeze the thread in case of no ping received for 5 seconds. So if this happens with you, you'll have to use isNetworkAvailable() method till then isOnline()
is better.
EDIT -
When looking in Android References, I found this:
void onDataConnectionStateChanged (int state)
This can be used to determine network state change.
Default states are:
DATA_DISCONNECTED
DATA_CONNECTING
DATA_CONNECTED
DATA_SUSPENDED