Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ConnectivityReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context ctx, Intent intent) {
- final ClockSync cs = ClockSync.getInstance();
- SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
- final boolean bootSync = prefs.getBoolean(BOOT_SYNC, false) && !cs.isBootSynced();
- final boolean autoSync = prefs.getBoolean(AUTO_SYNC, false);
- // no automatic or boot synchronization enabled, abort
- if (!bootSync && !autoSync) return;
- final NetworkStatus state = getNetworkState(ctx);
- final boolean canUseNetwork = state == NetworkStatus.CAN_USE_NETWORK;
- final int intState = canUseNetwork ? 1 : 0;
- // connection state didn't change, nothing to do
- if (cs.getCachedConnectionState() == intState) {
- return;
- }
- cs.setCachedConnectionState(intState);
- if (!canUseNetwork) {
- // if we can't use network, disable all alarm timers
- Log.d(ClockSync.TAG, "Network disabled, cancel timer");
- scheduleSynchronization(ctx, 0, true);
- } else {
- // when network is available again, schedule synchronization or sync instantly if missed last sync
- final long interval = Integer.parseInt(prefs.getString(SYNC_INTERVAL, DEFAULT_SYNC_INTERVAL)) * 1000L;
- final long now = System.currentTimeMillis();
- long lastSuccess = prefs.getLong(LAST_SUCCESS, 0L);
- // incorrect timestamp was saved
- if (lastSuccess > now) {
- lastSuccess = 0L;
- }
- // missed sync, or after hard reset now = 0, or on boot
- final boolean missedSync = now - lastSuccess > interval;
- final boolean clockReset = now < interval;
- if (missedSync || clockReset || bootSync) {
- if (missedSync) {
- Log.d(ClockSync.TAG, "Last synchronization missed (no network), sync now and set timer!");
- } else if (bootSync) {
- Log.d(ClockSync.TAG, "Sync on boot");
- }
- scheduleSynchronization(ctx, 0, false);
- WakefulIntentService.acquireStaticLock(ctx);
- ctx.startService(new Intent(ctx, SyncTaskService.class));
- } else {
- // should sync earlier than now + interval
- // now = 12:00 lastSuccess = 11:00 interval = 2h => sync @ 13:00, NOT at 12:00 + 2h = 14:00
- long firstSyncDelta = lastSuccess - now + interval;
- Log.d(ClockSync.TAG, "Network enabled, timer will fire in: " + firstSyncDelta / 1000);
- scheduleSynchronization(ctx, firstSyncDelta, false);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement