The following is a service that can do it. To be more understandable, it uses a CountDownTimer to handle the looping with an anonymous thread to keep the network operations off of the main thread. Ideally, these should probably be combined in a handler. Also, unless a better synchronization approach is applied to the 'sycing' guard condition, TIME_OUT_MSECS should be kept fairly small compared CHECK_FREQ_MSECS to avoid race conditions on checking vs. setting it.
package com.example.test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
public class NetCheckService extends Service {
private final static String TAG = "NetCheckService";
private final static long CHECK_FREQ_MSECS = 300000L; // 5 minutes
private final static int TIME_OUT_MSECS = 5000; // 5 seconds
private final static String IP_ADDR = "192.168.0.1";
private Boolean syncing = false;
CountDownTimer cdt = null;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting network check...");
cdt = new CountDownTimer(Long.MAX_VALUE, CHECK_FREQ_MSECS) {
@Override
public void onTick(long millisUntilFinished) {
// Don't check if we're already syncing.
if (syncing)
return;
Log.i(TAG, "Checking to see if IP address " + IP_ADDR + " is reachable...");
new Thread(new Runnable() {
@Override
public void run() {
try {
if (InetAddress.getByName(IP_ADDR).isReachable(TIME_OUT_MSECS))
doSync();
else
Log.i(TAG, "IP address is not reachable.");
} catch (UnknownHostException e) {
// Network wasn't reachable; ignore
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void onFinish() {
Log.i(TAG, "Nearly 300 million years have elapsed; this timer is tired.");
}
};
cdt.start();
}
@Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled.");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
private void doSync() {
syncing = true;
Log.i(TAG, "Synching ...");
// Do synchronization stuff
syncing = false;
}
}