Files

66 lines
2.5 KiB
Java

package org.gingercal;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
/** Runs a sync on a worker thread and broadcasts the outcome to whatever screen is open. */
public class SyncService extends IntentService {
public static final String STATE = "org.gingercal.SYNC_STATE";
public static volatile boolean running;
public SyncService() {
super("GingerCalSync");
}
@Override
protected void onHandleIntent(Intent intent) {
boolean manual = intent != null && intent.getBooleanExtra("manual", false);
boolean force = intent != null && intent.getBooleanExtra("force", false);
SharedPreferences p = App.prefs(this);
Dav dav = null;
try {
if (!App.configured(this)) return;
if (!manual && !App.online(this)) return;
running = true;
send("start", null, null);
dav = App.dav(this);
long now = System.currentTimeMillis();
Syncer.Result r = Syncer.sync(dav, Db.get(this), now, App.BACK_DAYS, App.ahead(this), force);
p.edit().putLong("lastsync", now).putString("status", r.summary()).putBoolean("error", false)
.putLong("win_from", r.from).putLong("win_to", r.to).commit();
send("done", r.summary(), null);
} catch (DavException.UntrustedCert u) {
p.edit().putString("status", u.getMessage()).putBoolean("error", true).commit();
send("error", u.getMessage(), u);
} catch (Throwable t) {
String msg = App.describe(t);
p.edit().putString("status", msg).putBoolean("error", true).commit();
send("error", msg, null);
} finally {
running = false;
if (dav != null) dav.close();
try {
Reminders.schedule(this);
} catch (RuntimeException ignored) {
}
AlarmReceiver.release();
}
}
void send(String state, String msg, DavException.UntrustedCert u) {
Intent b = new Intent(STATE);
b.setPackage(getPackageName());
b.putExtra("state", state);
if (msg != null) b.putExtra("msg", msg);
if (u != null) {
b.putExtra("fp", u.fingerprint);
b.putExtra("subject", u.subject);
b.putExtra("issuer", u.issuer);
b.putExtra("expires", u.expires);
b.putExtra("mismatch", u.pinMismatch);
}
sendBroadcast(b);
}
}