Advertisement
JetSerge

Untitled

Nov 19th, 2013
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. public class ConnectivityReceiver extends BroadcastReceiver {
  2. @Override
  3. public void onReceive(Context ctx, Intent intent) {
  4. final ClockSync cs = ClockSync.getInstance();
  5.  
  6. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
  7. final boolean bootSync = prefs.getBoolean(BOOT_SYNC, false) && !cs.isBootSynced();
  8. final boolean autoSync = prefs.getBoolean(AUTO_SYNC, false);
  9.  
  10. // no automatic or boot synchronization enabled, abort
  11. if (!bootSync && !autoSync) return;
  12.  
  13. final NetworkStatus state = getNetworkState(ctx);
  14. final boolean canUseNetwork = state == NetworkStatus.CAN_USE_NETWORK;
  15. final int intState = canUseNetwork ? 1 : 0;
  16.  
  17. // connection state didn't change, nothing to do
  18. if (cs.getCachedConnectionState() == intState) {
  19. return;
  20. }
  21. cs.setCachedConnectionState(intState);
  22.  
  23. if (!canUseNetwork) {
  24. // if we can't use network, disable all alarm timers
  25. Log.d(ClockSync.TAG, "Network disabled, cancel timer");
  26. scheduleSynchronization(ctx, 0, true);
  27. } else {
  28. // when network is available again, schedule synchronization or sync instantly if missed last sync
  29. final long interval = Integer.parseInt(prefs.getString(SYNC_INTERVAL, DEFAULT_SYNC_INTERVAL)) * 1000L;
  30. final long now = System.currentTimeMillis();
  31. long lastSuccess = prefs.getLong(LAST_SUCCESS, 0L);
  32. // incorrect timestamp was saved
  33. if (lastSuccess > now) {
  34. lastSuccess = 0L;
  35. }
  36. // missed sync, or after hard reset now = 0, or on boot
  37. final boolean missedSync = now - lastSuccess > interval;
  38. final boolean clockReset = now < interval;
  39. if (missedSync || clockReset || bootSync) {
  40. if (missedSync) {
  41. Log.d(ClockSync.TAG, "Last synchronization missed (no network), sync now and set timer!");
  42. } else if (bootSync) {
  43. Log.d(ClockSync.TAG, "Sync on boot");
  44. }
  45. scheduleSynchronization(ctx, 0, false);
  46. WakefulIntentService.acquireStaticLock(ctx);
  47. ctx.startService(new Intent(ctx, SyncTaskService.class));
  48. } else {
  49. // should sync earlier than now + interval
  50. // now = 12:00 lastSuccess = 11:00 interval = 2h => sync @ 13:00, NOT at 12:00 + 2h = 14:00
  51. long firstSyncDelta = lastSuccess - now + interval;
  52. Log.d(ClockSync.TAG, "Network enabled, timer will fire in: " + firstSyncDelta / 1000);
  53. scheduleSynchronization(ctx, firstSyncDelta, false);
  54. }
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement