I'm saving data to my embedded DB(Realm.io) and I want to continuous check if there is internet connection and if connection is OK check if there is data to sync with server, then synchronize data, remove synchronized data from embedded DB and set the state to "synchronized" until another data is added to my embedded DB.
It seems to check internet connection async. I need to implement BroadcastReciever:
Internet listener Android example
But I need to do this in any activity because maybe I retrieve internet connection when I change activity, I thought adding this broadcast reciever in every activity but looks dirty, how I can do this in a clean way? Is it possible to create a thread that have a broadcast reciever and if inet connection is ok persists data, and keep it alive until application is closed?
Now I'm Trying to do a permanent IntentService to check if DB need to be synchronized and if internet is available sync DB:
public class MyIntentService extends IntentService {
private PreferenceController preferenceController;
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
preferenceController = new PreferenceController(this);
int i = 0;
while (i >= 0) {
Log.d("ISERVICE", "checking number: " + i);
checkUpdate();
waitInSeconds(300);
i++;
}
}
private void waitInSeconds(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
private void checkUpdate() {
if (preferenceController.getBooleanPreference("SYNC_DB", false)) { // if DB need to be synchronized
if (isOnline()) { // if connected to internet
syncDatabases();
}
}
}
private void syncDatabases() {
// Do stuff to synchronize realm.io with server
}
/*
Recieve Broadcast if internet is available again and call checkUpdate()
*/
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
}