The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2008 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package android.content; |
| 18 | |
| 19 | import com.google.android.collect.Maps; |
| 20 | |
| 21 | import com.android.internal.R; |
| 22 | import com.android.internal.util.ArrayUtils; |
| 23 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 24 | import android.accounts.Account; |
| 25 | import android.accounts.AccountManager; |
| 26 | import android.accounts.OnAccountsUpdatedListener; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 27 | import android.app.AlarmManager; |
| 28 | import android.app.Notification; |
| 29 | import android.app.NotificationManager; |
| 30 | import android.app.PendingIntent; |
| 31 | import android.content.pm.ApplicationInfo; |
| 32 | import android.content.pm.IPackageManager; |
| 33 | import android.content.pm.PackageManager; |
| 34 | import android.content.pm.ProviderInfo; |
| 35 | import android.content.pm.ResolveInfo; |
| 36 | import android.database.Cursor; |
| 37 | import android.database.DatabaseUtils; |
| 38 | import android.net.ConnectivityManager; |
| 39 | import android.net.NetworkInfo; |
| 40 | import android.net.Uri; |
| 41 | import android.os.Bundle; |
| 42 | import android.os.Handler; |
| 43 | import android.os.HandlerThread; |
| 44 | import android.os.IBinder; |
| 45 | import android.os.Looper; |
| 46 | import android.os.Message; |
| 47 | import android.os.Parcel; |
| 48 | import android.os.PowerManager; |
| 49 | import android.os.Process; |
| 50 | import android.os.RemoteException; |
| 51 | import android.os.ServiceManager; |
| 52 | import android.os.SystemClock; |
| 53 | import android.os.SystemProperties; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 54 | import android.provider.Sync; |
| 55 | import android.provider.Settings; |
| 56 | import android.provider.Sync.History; |
| 57 | import android.text.TextUtils; |
| 58 | import android.text.format.DateUtils; |
| 59 | import android.text.format.Time; |
| 60 | import android.util.Config; |
| 61 | import android.util.EventLog; |
| 62 | import android.util.Log; |
| 63 | |
| 64 | import java.io.DataInputStream; |
| 65 | import java.io.DataOutputStream; |
| 66 | import java.io.File; |
| 67 | import java.io.FileDescriptor; |
| 68 | import java.io.FileInputStream; |
| 69 | import java.io.FileNotFoundException; |
| 70 | import java.io.FileOutputStream; |
| 71 | import java.io.IOException; |
| 72 | import java.io.PrintWriter; |
| 73 | import java.util.ArrayList; |
| 74 | import java.util.HashMap; |
| 75 | import java.util.Iterator; |
| 76 | import java.util.List; |
| 77 | import java.util.Map; |
| 78 | import java.util.PriorityQueue; |
| 79 | import java.util.Random; |
| 80 | import java.util.Observer; |
| 81 | import java.util.Observable; |
| 82 | |
| 83 | /** |
| 84 | * @hide |
| 85 | */ |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 86 | class SyncManager implements OnAccountsUpdatedListener { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 87 | private static final String TAG = "SyncManager"; |
| 88 | |
| 89 | // used during dumping of the Sync history |
| 90 | private static final long MILLIS_IN_HOUR = 1000 * 60 * 60; |
| 91 | private static final long MILLIS_IN_DAY = MILLIS_IN_HOUR * 24; |
| 92 | private static final long MILLIS_IN_WEEK = MILLIS_IN_DAY * 7; |
| 93 | private static final long MILLIS_IN_4WEEKS = MILLIS_IN_WEEK * 4; |
| 94 | |
| 95 | /** Delay a sync due to local changes this long. In milliseconds */ |
| 96 | private static final long LOCAL_SYNC_DELAY = 30 * 1000; // 30 seconds |
| 97 | |
| 98 | /** |
| 99 | * If a sync takes longer than this and the sync queue is not empty then we will |
| 100 | * cancel it and add it back to the end of the sync queue. In milliseconds. |
| 101 | */ |
| 102 | private static final long MAX_TIME_PER_SYNC = 5 * 60 * 1000; // 5 minutes |
| 103 | |
| 104 | private static final long SYNC_NOTIFICATION_DELAY = 30 * 1000; // 30 seconds |
| 105 | |
| 106 | /** |
| 107 | * When retrying a sync for the first time use this delay. After that |
| 108 | * the retry time will double until it reached MAX_SYNC_RETRY_TIME. |
| 109 | * In milliseconds. |
| 110 | */ |
| 111 | private static final long INITIAL_SYNC_RETRY_TIME_IN_MS = 30 * 1000; // 30 seconds |
| 112 | |
| 113 | /** |
| 114 | * Default the max sync retry time to this value. |
| 115 | */ |
| 116 | private static final long DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS = 60 * 60; // one hour |
| 117 | |
| 118 | /** |
| 119 | * An error notification is sent if sync of any of the providers has been failing for this long. |
| 120 | */ |
| 121 | private static final long ERROR_NOTIFICATION_DELAY_MS = 1000 * 60 * 10; // 10 minutes |
| 122 | |
| 123 | private static final String SYNC_WAKE_LOCK = "SyncManagerSyncWakeLock"; |
| 124 | private static final String HANDLE_SYNC_ALARM_WAKE_LOCK = "SyncManagerHandleSyncAlarmWakeLock"; |
| 125 | |
| 126 | private Context mContext; |
| 127 | private ContentResolver mContentResolver; |
| 128 | |
| 129 | private String mStatusText = ""; |
| 130 | private long mHeartbeatTime = 0; |
| 131 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 132 | private volatile Account[] mAccounts = null; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 133 | |
| 134 | volatile private PowerManager.WakeLock mSyncWakeLock; |
| 135 | volatile private PowerManager.WakeLock mHandleAlarmWakeLock; |
| 136 | volatile private boolean mDataConnectionIsConnected = false; |
| 137 | volatile private boolean mStorageIsLow = false; |
| 138 | private Sync.Settings.QueryMap mSyncSettings; |
| 139 | |
| 140 | private final NotificationManager mNotificationMgr; |
| 141 | private AlarmManager mAlarmService = null; |
| 142 | private HandlerThread mSyncThread; |
| 143 | |
| 144 | private volatile IPackageManager mPackageManager; |
| 145 | |
| 146 | private final SyncStorageEngine mSyncStorageEngine; |
| 147 | private final SyncQueue mSyncQueue; |
| 148 | |
| 149 | private ActiveSyncContext mActiveSyncContext = null; |
| 150 | |
| 151 | // set if the sync error indicator should be reported. |
| 152 | private boolean mNeedSyncErrorNotification = false; |
| 153 | // set if the sync active indicator should be reported |
| 154 | private boolean mNeedSyncActiveNotification = false; |
| 155 | |
| 156 | private volatile boolean mSyncPollInitialized; |
| 157 | private final PendingIntent mSyncAlarmIntent; |
| 158 | private final PendingIntent mSyncPollAlarmIntent; |
| 159 | |
| 160 | private BroadcastReceiver mStorageIntentReceiver = |
| 161 | new BroadcastReceiver() { |
| 162 | public void onReceive(Context context, Intent intent) { |
| 163 | ensureContentResolver(); |
| 164 | String action = intent.getAction(); |
| 165 | if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) { |
| 166 | if (Log.isLoggable(TAG, Log.VERBOSE)) { |
| 167 | Log.v(TAG, "Internal storage is low."); |
| 168 | } |
| 169 | mStorageIsLow = true; |
| 170 | cancelActiveSync(null /* no url */); |
| 171 | } else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) { |
| 172 | if (Log.isLoggable(TAG, Log.VERBOSE)) { |
| 173 | Log.v(TAG, "Internal storage is ok."); |
| 174 | } |
| 175 | mStorageIsLow = false; |
| 176 | sendCheckAlarmsMessage(); |
| 177 | } |
| 178 | } |
| 179 | }; |
| 180 | |
Fred Quintana | 6030734 | 2009-03-24 22:48:12 -0700 | [diff] [blame] | 181 | private BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() { |
| 182 | public void onReceive(Context context, Intent intent) { |
| 183 | if (!mFactoryTest) { |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 184 | AccountManager.get(mContext).addOnAccountsUpdatedListener(SyncManager.this, |
| 185 | mSyncHandler, true /* updateImmediately */); |
Fred Quintana | 6030734 | 2009-03-24 22:48:12 -0700 | [diff] [blame] | 186 | } |
| 187 | } |
| 188 | }; |
| 189 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 190 | public void onAccountsUpdated(Account[] accounts) { |
| 191 | final boolean hadAccountsAlready = mAccounts != null; |
| 192 | mAccounts = accounts; |
| 193 | |
| 194 | // if a sync is in progress yet it is no longer in the accounts list, |
| 195 | // cancel it |
| 196 | ActiveSyncContext activeSyncContext = mActiveSyncContext; |
| 197 | if (activeSyncContext != null) { |
| 198 | if (!ArrayUtils.contains(accounts, activeSyncContext.mSyncOperation.account)) { |
| 199 | Log.d(TAG, "canceling sync since the account has been removed"); |
| 200 | sendSyncFinishedOrCanceledMessage(activeSyncContext, |
| 201 | null /* no result since this is a cancel */); |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | // we must do this since we don't bother scheduling alarms when |
| 206 | // the accounts are not set yet |
| 207 | sendCheckAlarmsMessage(); |
| 208 | |
| 209 | mSyncStorageEngine.doDatabaseCleanup(accounts); |
| 210 | |
| 211 | if (hadAccountsAlready && accounts.length > 0) { |
| 212 | // request a sync so that if the password was changed we will |
| 213 | // retry any sync that failed when it was wrong |
| 214 | startSync(null /* all providers */, null /* no extras */); |
| 215 | } |
| 216 | } |
| 217 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 218 | private BroadcastReceiver mConnectivityIntentReceiver = |
| 219 | new BroadcastReceiver() { |
| 220 | public void onReceive(Context context, Intent intent) { |
| 221 | NetworkInfo networkInfo = |
| 222 | intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); |
| 223 | NetworkInfo.State state = (networkInfo == null ? NetworkInfo.State.UNKNOWN : |
| 224 | networkInfo.getState()); |
| 225 | if (Log.isLoggable(TAG, Log.VERBOSE)) { |
| 226 | Log.v(TAG, "received connectivity action. network info: " + networkInfo); |
| 227 | } |
| 228 | |
| 229 | // only pay attention to the CONNECTED and DISCONNECTED states. |
| 230 | // if connected, we are connected. |
| 231 | // if disconnected, we may not be connected. in some cases, we may be connected on |
| 232 | // a different network. |
| 233 | // e.g., if switching from GPRS to WiFi, we may receive the CONNECTED to WiFi and |
| 234 | // DISCONNECTED for GPRS in any order. if we receive the CONNECTED first, and then |
| 235 | // a DISCONNECTED, we want to make sure we set mDataConnectionIsConnected to true |
| 236 | // since we still have a WiFi connection. |
| 237 | switch (state) { |
| 238 | case CONNECTED: |
| 239 | mDataConnectionIsConnected = true; |
| 240 | break; |
| 241 | case DISCONNECTED: |
| 242 | if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) { |
| 243 | mDataConnectionIsConnected = false; |
| 244 | } else { |
| 245 | mDataConnectionIsConnected = true; |
| 246 | } |
| 247 | break; |
| 248 | default: |
| 249 | // ignore the rest of the states -- leave our boolean alone. |
| 250 | } |
| 251 | if (mDataConnectionIsConnected) { |
| 252 | initializeSyncPoll(); |
| 253 | sendCheckAlarmsMessage(); |
| 254 | } |
| 255 | } |
| 256 | }; |
| 257 | |
| 258 | private static final String ACTION_SYNC_ALARM = "android.content.syncmanager.SYNC_ALARM"; |
| 259 | private static final String SYNC_POLL_ALARM = "android.content.syncmanager.SYNC_POLL_ALARM"; |
| 260 | private final SyncHandler mSyncHandler; |
| 261 | |
| 262 | private static final String[] SYNC_ACTIVE_PROJECTION = new String[]{ |
| 263 | Sync.Active.ACCOUNT, |
| 264 | Sync.Active.AUTHORITY, |
| 265 | Sync.Active.START_TIME, |
| 266 | }; |
| 267 | |
| 268 | private static final String[] SYNC_PENDING_PROJECTION = new String[]{ |
| 269 | Sync.Pending.ACCOUNT, |
| 270 | Sync.Pending.AUTHORITY |
| 271 | }; |
| 272 | |
| 273 | private static final int MAX_SYNC_POLL_DELAY_SECONDS = 36 * 60 * 60; // 36 hours |
| 274 | private static final int MIN_SYNC_POLL_DELAY_SECONDS = 24 * 60 * 60; // 24 hours |
| 275 | |
| 276 | private static final String SYNCMANAGER_PREFS_FILENAME = "/data/system/syncmanager.prefs"; |
| 277 | |
Fred Quintana | 6030734 | 2009-03-24 22:48:12 -0700 | [diff] [blame] | 278 | private final boolean mFactoryTest; |
| 279 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 280 | public SyncManager(Context context, boolean factoryTest) { |
Fred Quintana | 6030734 | 2009-03-24 22:48:12 -0700 | [diff] [blame] | 281 | mFactoryTest = factoryTest; |
| 282 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 283 | // Initialize the SyncStorageEngine first, before registering observers |
| 284 | // and creating threads and so on; it may fail if the disk is full. |
| 285 | SyncStorageEngine.init(context); |
| 286 | mSyncStorageEngine = SyncStorageEngine.getSingleton(); |
| 287 | mSyncQueue = new SyncQueue(mSyncStorageEngine); |
| 288 | |
| 289 | mContext = context; |
| 290 | |
| 291 | mSyncThread = new HandlerThread("SyncHandlerThread", Process.THREAD_PRIORITY_BACKGROUND); |
| 292 | mSyncThread.start(); |
| 293 | mSyncHandler = new SyncHandler(mSyncThread.getLooper()); |
| 294 | |
| 295 | mPackageManager = null; |
| 296 | |
| 297 | mSyncAlarmIntent = PendingIntent.getBroadcast( |
| 298 | mContext, 0 /* ignored */, new Intent(ACTION_SYNC_ALARM), 0); |
| 299 | |
| 300 | mSyncPollAlarmIntent = PendingIntent.getBroadcast( |
| 301 | mContext, 0 /* ignored */, new Intent(SYNC_POLL_ALARM), 0); |
| 302 | |
| 303 | IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); |
| 304 | context.registerReceiver(mConnectivityIntentReceiver, intentFilter); |
| 305 | |
Fred Quintana | 6030734 | 2009-03-24 22:48:12 -0700 | [diff] [blame] | 306 | intentFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED); |
| 307 | context.registerReceiver(mBootCompletedReceiver, intentFilter); |
| 308 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 309 | intentFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW); |
| 310 | intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK); |
| 311 | context.registerReceiver(mStorageIntentReceiver, intentFilter); |
| 312 | |
| 313 | if (!factoryTest) { |
| 314 | mNotificationMgr = (NotificationManager) |
| 315 | context.getSystemService(Context.NOTIFICATION_SERVICE); |
| 316 | context.registerReceiver(new SyncAlarmIntentReceiver(), |
| 317 | new IntentFilter(ACTION_SYNC_ALARM)); |
| 318 | } else { |
| 319 | mNotificationMgr = null; |
| 320 | } |
| 321 | PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); |
| 322 | mSyncWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, SYNC_WAKE_LOCK); |
| 323 | mSyncWakeLock.setReferenceCounted(false); |
| 324 | |
| 325 | // This WakeLock is used to ensure that we stay awake between the time that we receive |
| 326 | // a sync alarm notification and when we finish processing it. We need to do this |
| 327 | // because we don't do the work in the alarm handler, rather we do it in a message |
| 328 | // handler. |
| 329 | mHandleAlarmWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, |
| 330 | HANDLE_SYNC_ALARM_WAKE_LOCK); |
| 331 | mHandleAlarmWakeLock.setReferenceCounted(false); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 332 | } |
| 333 | |
| 334 | private synchronized void initializeSyncPoll() { |
| 335 | if (mSyncPollInitialized) return; |
| 336 | mSyncPollInitialized = true; |
| 337 | |
| 338 | mContext.registerReceiver(new SyncPollAlarmReceiver(), new IntentFilter(SYNC_POLL_ALARM)); |
| 339 | |
| 340 | // load the next poll time from shared preferences |
| 341 | long absoluteAlarmTime = readSyncPollTime(); |
| 342 | |
| 343 | if (Log.isLoggable(TAG, Log.VERBOSE)) { |
| 344 | Log.v(TAG, "initializeSyncPoll: absoluteAlarmTime is " + absoluteAlarmTime); |
| 345 | } |
| 346 | |
| 347 | // Convert absoluteAlarmTime to elapsed realtime. If this time was in the past then |
| 348 | // schedule the poll immediately, if it is too far in the future then cap it at |
| 349 | // MAX_SYNC_POLL_DELAY_SECONDS. |
| 350 | long absoluteNow = System.currentTimeMillis(); |
| 351 | long relativeNow = SystemClock.elapsedRealtime(); |
| 352 | long relativeAlarmTime = relativeNow; |
| 353 | if (absoluteAlarmTime > absoluteNow) { |
| 354 | long delayInMs = absoluteAlarmTime - absoluteNow; |
| 355 | final int maxDelayInMs = MAX_SYNC_POLL_DELAY_SECONDS * 1000; |
| 356 | if (delayInMs > maxDelayInMs) { |
| 357 | delayInMs = MAX_SYNC_POLL_DELAY_SECONDS * 1000; |
| 358 | } |
| 359 | relativeAlarmTime += delayInMs; |
| 360 | } |
| 361 | |
| 362 | // schedule an alarm for the next poll time |
| 363 | scheduleSyncPollAlarm(relativeAlarmTime); |
| 364 | } |
| 365 | |
| 366 | private void scheduleSyncPollAlarm(long relativeAlarmTime) { |
| 367 | if (Log.isLoggable(TAG, Log.VERBOSE)) { |
| 368 | Log.v(TAG, "scheduleSyncPollAlarm: relativeAlarmTime is " + relativeAlarmTime |
| 369 | + ", now is " + SystemClock.elapsedRealtime() |
| 370 | + ", delay is " + (relativeAlarmTime - SystemClock.elapsedRealtime())); |
| 371 | } |
| 372 | ensureAlarmService(); |
| 373 | mAlarmService.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, relativeAlarmTime, |
| 374 | mSyncPollAlarmIntent); |
| 375 | } |
| 376 | |
| 377 | /** |
| 378 | * Return a random value v that satisfies minValue <= v < maxValue. The difference between |
| 379 | * maxValue and minValue must be less than Integer.MAX_VALUE. |
| 380 | */ |
| 381 | private long jitterize(long minValue, long maxValue) { |
| 382 | Random random = new Random(SystemClock.elapsedRealtime()); |
| 383 | long spread = maxValue - minValue; |
| 384 | if (spread > Integer.MAX_VALUE) { |
| 385 | throw new IllegalArgumentException("the difference between the maxValue and the " |
| 386 | + "minValue must be less than " + Integer.MAX_VALUE); |
| 387 | } |
| 388 | return minValue + random.nextInt((int)spread); |
| 389 | } |
| 390 | |
| 391 | private void handleSyncPollAlarm() { |
| 392 | // determine the next poll time |
| 393 | long delayMs = jitterize(MIN_SYNC_POLL_DELAY_SECONDS, MAX_SYNC_POLL_DELAY_SECONDS) * 1000; |
| 394 | long nextRelativePollTimeMs = SystemClock.elapsedRealtime() + delayMs; |
| 395 | |
| 396 | if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "handleSyncPollAlarm: delay " + delayMs); |
| 397 | |
| 398 | // write the absolute time to shared preferences |
| 399 | writeSyncPollTime(System.currentTimeMillis() + delayMs); |
| 400 | |
| 401 | // schedule an alarm for the next poll time |
| 402 | scheduleSyncPollAlarm(nextRelativePollTimeMs); |
| 403 | |
| 404 | // perform a poll |
| 405 | scheduleSync(null /* sync all syncable providers */, new Bundle(), 0 /* no delay */); |
| 406 | } |
| 407 | |
| 408 | private void writeSyncPollTime(long when) { |
| 409 | File f = new File(SYNCMANAGER_PREFS_FILENAME); |
| 410 | DataOutputStream str = null; |
| 411 | try { |
| 412 | str = new DataOutputStream(new FileOutputStream(f)); |
| 413 | str.writeLong(when); |
| 414 | } catch (FileNotFoundException e) { |
| 415 | Log.w(TAG, "error writing to file " + f, e); |
| 416 | } catch (IOException e) { |
| 417 | Log.w(TAG, "error writing to file " + f, e); |
| 418 | } finally { |
| 419 | if (str != null) { |
| 420 | try { |
| 421 | str.close(); |
| 422 | } catch (IOException e) { |
| 423 | Log.w(TAG, "error closing file " + f, e); |
| 424 | } |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | private long readSyncPollTime() { |
| 430 | File f = new File(SYNCMANAGER_PREFS_FILENAME); |
| 431 | |
| 432 | DataInputStream str = null; |
| 433 | try { |
| 434 | str = new DataInputStream(new FileInputStream(f)); |
| 435 | return str.readLong(); |
| 436 | } catch (FileNotFoundException e) { |
| 437 | writeSyncPollTime(0); |
| 438 | } catch (IOException e) { |
| 439 | Log.w(TAG, "error reading file " + f, e); |
| 440 | } finally { |
| 441 | if (str != null) { |
| 442 | try { |
| 443 | str.close(); |
| 444 | } catch (IOException e) { |
| 445 | Log.w(TAG, "error closing file " + f, e); |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | return 0; |
| 450 | } |
| 451 | |
| 452 | public ActiveSyncContext getActiveSyncContext() { |
| 453 | return mActiveSyncContext; |
| 454 | } |
| 455 | |
| 456 | private Sync.Settings.QueryMap getSyncSettings() { |
| 457 | if (mSyncSettings == null) { |
| 458 | mSyncSettings = new Sync.Settings.QueryMap(mContext.getContentResolver(), true, |
| 459 | new Handler()); |
| 460 | mSyncSettings.addObserver(new Observer(){ |
| 461 | public void update(Observable o, Object arg) { |
| 462 | // force the sync loop to run if the settings change |
| 463 | sendCheckAlarmsMessage(); |
| 464 | } |
| 465 | }); |
| 466 | } |
| 467 | return mSyncSettings; |
| 468 | } |
| 469 | |
| 470 | private void ensureContentResolver() { |
| 471 | if (mContentResolver == null) { |
| 472 | mContentResolver = mContext.getContentResolver(); |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | private void ensureAlarmService() { |
| 477 | if (mAlarmService == null) { |
| 478 | mAlarmService = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE); |
| 479 | } |
| 480 | } |
| 481 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 482 | public Account getSyncingAccount() { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 483 | ActiveSyncContext activeSyncContext = mActiveSyncContext; |
| 484 | return (activeSyncContext != null) ? activeSyncContext.mSyncOperation.account : null; |
| 485 | } |
| 486 | |
| 487 | /** |
| 488 | * Returns whether or not sync is enabled. Sync can be enabled by |
| 489 | * setting the system property "ro.config.sync" to the value "yes". |
| 490 | * This is normally done at boot time on builds that support sync. |
| 491 | * @return true if sync is enabled |
| 492 | */ |
| 493 | private boolean isSyncEnabled() { |
| 494 | // Require the precise value "yes" to discourage accidental activation. |
| 495 | return "yes".equals(SystemProperties.get("ro.config.sync")); |
| 496 | } |
| 497 | |
| 498 | /** |
| 499 | * Initiate a sync. This can start a sync for all providers |
| 500 | * (pass null to url, set onlyTicklable to false), only those |
| 501 | * providers that are marked as ticklable (pass null to url, |
| 502 | * set onlyTicklable to true), or a specific provider (set url |
| 503 | * to the content url of the provider). |
| 504 | * |
| 505 | * <p>If the ContentResolver.SYNC_EXTRAS_UPLOAD boolean in extras is |
| 506 | * true then initiate a sync that just checks for local changes to send |
| 507 | * to the server, otherwise initiate a sync that first gets any |
| 508 | * changes from the server before sending local changes back to |
| 509 | * the server. |
| 510 | * |
| 511 | * <p>If a specific provider is being synced (the url is non-null) |
| 512 | * then the extras can contain SyncAdapter-specific information |
| 513 | * to control what gets synced (e.g. which specific feed to sync). |
| 514 | * |
| 515 | * <p>You'll start getting callbacks after this. |
| 516 | * |
| 517 | * @param url The Uri of a specific provider to be synced, or |
| 518 | * null to sync all providers. |
| 519 | * @param extras a Map of SyncAdapter-specific information to control |
| 520 | * syncs of a specific provider. Can be null. Is ignored |
| 521 | * if the url is null. |
| 522 | * @param delay how many milliseconds in the future to wait before performing this |
| 523 | * sync. -1 means to make this the next sync to perform. |
| 524 | */ |
| 525 | public void scheduleSync(Uri url, Bundle extras, long delay) { |
| 526 | boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE); |
| 527 | if (isLoggable) { |
| 528 | Log.v(TAG, "scheduleSync:" |
| 529 | + " delay " + delay |
| 530 | + ", url " + ((url == null) ? "(null)" : url) |
| 531 | + ", extras " + ((extras == null) ? "(null)" : extras)); |
| 532 | } |
| 533 | |
| 534 | if (!isSyncEnabled()) { |
| 535 | if (isLoggable) { |
| 536 | Log.v(TAG, "not syncing because sync is disabled"); |
| 537 | } |
| 538 | setStatusText("Sync is disabled."); |
| 539 | return; |
| 540 | } |
| 541 | |
| 542 | if (mAccounts == null) setStatusText("The accounts aren't known yet."); |
| 543 | if (!mDataConnectionIsConnected) setStatusText("No data connection"); |
| 544 | if (mStorageIsLow) setStatusText("Memory low"); |
| 545 | |
| 546 | if (extras == null) extras = new Bundle(); |
| 547 | |
| 548 | Boolean expedited = extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false); |
| 549 | if (expedited) { |
| 550 | delay = -1; // this means schedule at the front of the queue |
| 551 | } |
| 552 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 553 | Account[] accounts; |
| 554 | Account accountFromExtras = extras.getParcelable(ContentResolver.SYNC_EXTRAS_ACCOUNT); |
| 555 | if (accountFromExtras != null) { |
| 556 | accounts = new Account[]{accountFromExtras}; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 557 | } else { |
| 558 | // if the accounts aren't configured yet then we can't support an account-less |
| 559 | // sync request |
| 560 | accounts = mAccounts; |
| 561 | if (accounts == null) { |
| 562 | // not ready yet |
| 563 | if (isLoggable) { |
| 564 | Log.v(TAG, "scheduleSync: no accounts yet, dropping"); |
| 565 | } |
| 566 | return; |
| 567 | } |
| 568 | if (accounts.length == 0) { |
| 569 | if (isLoggable) { |
| 570 | Log.v(TAG, "scheduleSync: no accounts configured, dropping"); |
| 571 | } |
| 572 | setStatusText("No accounts are configured."); |
| 573 | return; |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); |
| 578 | final boolean force = extras.getBoolean(ContentResolver.SYNC_EXTRAS_FORCE, false); |
| 579 | |
| 580 | int source; |
| 581 | if (uploadOnly) { |
| 582 | source = Sync.History.SOURCE_LOCAL; |
| 583 | } else if (force) { |
| 584 | source = Sync.History.SOURCE_USER; |
| 585 | } else if (url == null) { |
| 586 | source = Sync.History.SOURCE_POLL; |
| 587 | } else { |
| 588 | // this isn't strictly server, since arbitrary callers can (and do) request |
| 589 | // a non-forced two-way sync on a specific url |
| 590 | source = Sync.History.SOURCE_SERVER; |
| 591 | } |
| 592 | |
| 593 | List<String> names = new ArrayList<String>(); |
| 594 | List<ProviderInfo> providers = new ArrayList<ProviderInfo>(); |
| 595 | populateProvidersList(url, names, providers); |
| 596 | |
| 597 | final int numProviders = providers.size(); |
| 598 | for (int i = 0; i < numProviders; i++) { |
| 599 | if (!providers.get(i).isSyncable) continue; |
| 600 | final String name = names.get(i); |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 601 | for (Account account : accounts) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 602 | scheduleSyncOperation(new SyncOperation(account, source, name, extras, delay)); |
| 603 | // TODO: remove this when Calendar supports multiple accounts. Until then |
| 604 | // pretend that only the first account exists when syncing calendar. |
| 605 | if ("calendar".equals(name)) { |
| 606 | break; |
| 607 | } |
| 608 | } |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | private void setStatusText(String message) { |
| 613 | mStatusText = message; |
| 614 | } |
| 615 | |
| 616 | private void populateProvidersList(Uri url, List<String> names, List<ProviderInfo> providers) { |
| 617 | try { |
| 618 | final IPackageManager packageManager = getPackageManager(); |
| 619 | if (url == null) { |
| 620 | packageManager.querySyncProviders(names, providers); |
| 621 | } else { |
| 622 | final String authority = url.getAuthority(); |
| 623 | ProviderInfo info = packageManager.resolveContentProvider(url.getAuthority(), 0); |
| 624 | if (info != null) { |
| 625 | // only set this provider if the requested authority is the primary authority |
| 626 | String[] providerNames = info.authority.split(";"); |
| 627 | if (url.getAuthority().equals(providerNames[0])) { |
| 628 | names.add(authority); |
| 629 | providers.add(info); |
| 630 | } |
| 631 | } |
| 632 | } |
| 633 | } catch (RemoteException ex) { |
| 634 | // we should really never get this, but if we do then clear the lists, which |
| 635 | // will result in the dropping of the sync request |
| 636 | Log.e(TAG, "error trying to get the ProviderInfo for " + url, ex); |
| 637 | names.clear(); |
| 638 | providers.clear(); |
| 639 | } |
| 640 | } |
| 641 | |
| 642 | public void scheduleLocalSync(Uri url) { |
| 643 | final Bundle extras = new Bundle(); |
| 644 | extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, true); |
| 645 | scheduleSync(url, extras, LOCAL_SYNC_DELAY); |
| 646 | } |
| 647 | |
| 648 | private IPackageManager getPackageManager() { |
| 649 | // Don't bother synchronizing on this. The worst that can happen is that two threads |
| 650 | // can try to get the package manager at the same time but only one result gets |
| 651 | // used. Since there is only one package manager in the system this doesn't matter. |
| 652 | if (mPackageManager == null) { |
| 653 | IBinder b = ServiceManager.getService("package"); |
| 654 | mPackageManager = IPackageManager.Stub.asInterface(b); |
| 655 | } |
| 656 | return mPackageManager; |
| 657 | } |
| 658 | |
| 659 | /** |
| 660 | * Initiate a sync for this given URL, or pass null for a full sync. |
| 661 | * |
| 662 | * <p>You'll start getting callbacks after this. |
| 663 | * |
| 664 | * @param url The Uri of a specific provider to be synced, or |
| 665 | * null to sync all providers. |
| 666 | * @param extras a Map of SyncAdapter specific information to control |
| 667 | * syncs of a specific provider. Can be null. Is ignored |
| 668 | */ |
| 669 | public void startSync(Uri url, Bundle extras) { |
| 670 | scheduleSync(url, extras, 0 /* no delay */); |
| 671 | } |
| 672 | |
| 673 | public void updateHeartbeatTime() { |
| 674 | mHeartbeatTime = SystemClock.elapsedRealtime(); |
| 675 | ensureContentResolver(); |
| 676 | mContentResolver.notifyChange(Sync.Active.CONTENT_URI, |
| 677 | null /* this change wasn't made through an observer */); |
| 678 | } |
| 679 | |
| 680 | private void sendSyncAlarmMessage() { |
| 681 | if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_ALARM"); |
| 682 | mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_SYNC_ALARM); |
| 683 | } |
| 684 | |
| 685 | private void sendCheckAlarmsMessage() { |
| 686 | if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_CHECK_ALARMS"); |
| 687 | mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_CHECK_ALARMS); |
| 688 | } |
| 689 | |
| 690 | private void sendSyncFinishedOrCanceledMessage(ActiveSyncContext syncContext, |
| 691 | SyncResult syncResult) { |
| 692 | if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_FINISHED"); |
| 693 | Message msg = mSyncHandler.obtainMessage(); |
| 694 | msg.what = SyncHandler.MESSAGE_SYNC_FINISHED; |
| 695 | msg.obj = new SyncHandlerMessagePayload(syncContext, syncResult); |
| 696 | mSyncHandler.sendMessage(msg); |
| 697 | } |
| 698 | |
| 699 | class SyncHandlerMessagePayload { |
| 700 | public final ActiveSyncContext activeSyncContext; |
| 701 | public final SyncResult syncResult; |
| 702 | |
| 703 | SyncHandlerMessagePayload(ActiveSyncContext syncContext, SyncResult syncResult) { |
| 704 | this.activeSyncContext = syncContext; |
| 705 | this.syncResult = syncResult; |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | class SyncAlarmIntentReceiver extends BroadcastReceiver { |
| 710 | public void onReceive(Context context, Intent intent) { |
| 711 | mHandleAlarmWakeLock.acquire(); |
| 712 | sendSyncAlarmMessage(); |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | class SyncPollAlarmReceiver extends BroadcastReceiver { |
| 717 | public void onReceive(Context context, Intent intent) { |
| 718 | handleSyncPollAlarm(); |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | private void rescheduleImmediately(SyncOperation syncOperation) { |
| 723 | SyncOperation rescheduledSyncOperation = new SyncOperation(syncOperation); |
| 724 | rescheduledSyncOperation.setDelay(0); |
| 725 | scheduleSyncOperation(rescheduledSyncOperation); |
| 726 | } |
| 727 | |
| 728 | private long rescheduleWithDelay(SyncOperation syncOperation) { |
| 729 | long newDelayInMs; |
| 730 | |
| 731 | if (syncOperation.delay == 0) { |
| 732 | // The initial delay is the jitterized INITIAL_SYNC_RETRY_TIME_IN_MS |
| 733 | newDelayInMs = jitterize(INITIAL_SYNC_RETRY_TIME_IN_MS, |
| 734 | (long)(INITIAL_SYNC_RETRY_TIME_IN_MS * 1.1)); |
| 735 | } else { |
| 736 | // Subsequent delays are the double of the previous delay |
| 737 | newDelayInMs = syncOperation.delay * 2; |
| 738 | } |
| 739 | |
| 740 | // Cap the delay |
| 741 | ensureContentResolver(); |
| 742 | long maxSyncRetryTimeInSeconds = Settings.Gservices.getLong(mContentResolver, |
| 743 | Settings.Gservices.SYNC_MAX_RETRY_DELAY_IN_SECONDS, |
| 744 | DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS); |
| 745 | if (newDelayInMs > maxSyncRetryTimeInSeconds * 1000) { |
| 746 | newDelayInMs = maxSyncRetryTimeInSeconds * 1000; |
| 747 | } |
| 748 | |
| 749 | SyncOperation rescheduledSyncOperation = new SyncOperation(syncOperation); |
| 750 | rescheduledSyncOperation.setDelay(newDelayInMs); |
| 751 | scheduleSyncOperation(rescheduledSyncOperation); |
| 752 | return newDelayInMs; |
| 753 | } |
| 754 | |
| 755 | /** |
| 756 | * Cancel the active sync if it matches the uri. The uri corresponds to the one passed |
| 757 | * in to startSync(). |
| 758 | * @param uri If non-null, the active sync is only canceled if it matches the uri. |
| 759 | * If null, any active sync is canceled. |
| 760 | */ |
| 761 | public void cancelActiveSync(Uri uri) { |
| 762 | ActiveSyncContext activeSyncContext = mActiveSyncContext; |
| 763 | if (activeSyncContext != null) { |
| 764 | // if a Uri was specified then only cancel the sync if it matches the the uri |
| 765 | if (uri != null) { |
| 766 | if (!uri.getAuthority().equals(activeSyncContext.mSyncOperation.authority)) { |
| 767 | return; |
| 768 | } |
| 769 | } |
| 770 | sendSyncFinishedOrCanceledMessage(activeSyncContext, |
| 771 | null /* no result since this is a cancel */); |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | /** |
| 776 | * Create and schedule a SyncOperation. |
| 777 | * |
| 778 | * @param syncOperation the SyncOperation to schedule |
| 779 | */ |
| 780 | public void scheduleSyncOperation(SyncOperation syncOperation) { |
| 781 | // If this operation is expedited and there is a sync in progress then |
| 782 | // reschedule the current operation and send a cancel for it. |
| 783 | final boolean expedited = syncOperation.delay < 0; |
| 784 | final ActiveSyncContext activeSyncContext = mActiveSyncContext; |
| 785 | if (expedited && activeSyncContext != null) { |
| 786 | final boolean activeIsExpedited = activeSyncContext.mSyncOperation.delay < 0; |
| 787 | final boolean hasSameKey = |
| 788 | activeSyncContext.mSyncOperation.key.equals(syncOperation.key); |
| 789 | // This request is expedited and there is a sync in progress. |
| 790 | // Interrupt the current sync only if it is not expedited and if it has a different |
| 791 | // key than the one we are scheduling. |
| 792 | if (!activeIsExpedited && !hasSameKey) { |
| 793 | rescheduleImmediately(activeSyncContext.mSyncOperation); |
| 794 | sendSyncFinishedOrCanceledMessage(activeSyncContext, |
| 795 | null /* no result since this is a cancel */); |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | boolean operationEnqueued; |
| 800 | synchronized (mSyncQueue) { |
| 801 | operationEnqueued = mSyncQueue.add(syncOperation); |
| 802 | } |
| 803 | |
| 804 | if (operationEnqueued) { |
| 805 | if (Log.isLoggable(TAG, Log.VERBOSE)) { |
| 806 | Log.v(TAG, "scheduleSyncOperation: enqueued " + syncOperation); |
| 807 | } |
| 808 | sendCheckAlarmsMessage(); |
| 809 | } else { |
| 810 | if (Log.isLoggable(TAG, Log.VERBOSE)) { |
| 811 | Log.v(TAG, "scheduleSyncOperation: dropping duplicate sync operation " |
| 812 | + syncOperation); |
| 813 | } |
| 814 | } |
| 815 | } |
| 816 | |
| 817 | /** |
| 818 | * Remove any scheduled sync operations that match uri. The uri corresponds to the one passed |
| 819 | * in to startSync(). |
| 820 | * @param uri If non-null, only operations that match the uri are cleared. |
| 821 | * If null, all operations are cleared. |
| 822 | */ |
| 823 | public void clearScheduledSyncOperations(Uri uri) { |
| 824 | synchronized (mSyncQueue) { |
| 825 | mSyncQueue.clear(null, uri != null ? uri.getAuthority() : null); |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | void maybeRescheduleSync(SyncResult syncResult, SyncOperation previousSyncOperation) { |
| 830 | boolean isLoggable = Log.isLoggable(TAG, Log.DEBUG); |
| 831 | if (isLoggable) { |
| 832 | Log.d(TAG, "encountered error(s) during the sync: " + syncResult + ", " |
| 833 | + previousSyncOperation); |
| 834 | } |
| 835 | |
| 836 | // If the operation succeeded to some extent then retry immediately. |
| 837 | // If this was a two-way sync then retry soft errors with an exponential backoff. |
| 838 | // If this was an upward sync then schedule a two-way sync immediately. |
| 839 | // Otherwise do not reschedule. |
| 840 | |
| 841 | if (syncResult.madeSomeProgress()) { |
| 842 | if (isLoggable) { |
| 843 | Log.d(TAG, "retrying sync operation immediately because " |
| 844 | + "even though it had an error it achieved some success"); |
| 845 | } |
| 846 | rescheduleImmediately(previousSyncOperation); |
| 847 | } else if (previousSyncOperation.extras.getBoolean( |
| 848 | ContentResolver.SYNC_EXTRAS_UPLOAD, false)) { |
| 849 | final SyncOperation newSyncOperation = new SyncOperation(previousSyncOperation); |
| 850 | newSyncOperation.extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); |
| 851 | newSyncOperation.setDelay(0); |
| 852 | if (Config.LOGD) { |
| 853 | Log.d(TAG, "retrying sync operation as a two-way sync because an upload-only sync " |
| 854 | + "encountered an error: " + previousSyncOperation); |
| 855 | } |
| 856 | scheduleSyncOperation(newSyncOperation); |
| 857 | } else if (syncResult.hasSoftError()) { |
| 858 | long delay = rescheduleWithDelay(previousSyncOperation); |
| 859 | if (delay >= 0) { |
| 860 | if (isLoggable) { |
| 861 | Log.d(TAG, "retrying sync operation in " + delay + " ms because " |
| 862 | + "it encountered a soft error: " + previousSyncOperation); |
| 863 | } |
| 864 | } |
| 865 | } else { |
| 866 | if (Config.LOGD) { |
| 867 | Log.d(TAG, "not retrying sync operation because the error is a hard error: " |
| 868 | + previousSyncOperation); |
| 869 | } |
| 870 | } |
| 871 | } |
| 872 | |
| 873 | /** |
| 874 | * Value type that represents a sync operation. |
| 875 | */ |
| 876 | static class SyncOperation implements Comparable { |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 877 | final Account account; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 878 | int syncSource; |
| 879 | String authority; |
| 880 | Bundle extras; |
| 881 | final String key; |
| 882 | long earliestRunTime; |
| 883 | long delay; |
| 884 | Long rowId = null; |
| 885 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 886 | SyncOperation(Account account, int source, String authority, Bundle extras, long delay) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 887 | this.account = account; |
| 888 | this.syncSource = source; |
| 889 | this.authority = authority; |
| 890 | this.extras = new Bundle(extras); |
| 891 | this.setDelay(delay); |
| 892 | this.key = toKey(); |
| 893 | } |
| 894 | |
| 895 | SyncOperation(SyncOperation other) { |
| 896 | this.account = other.account; |
| 897 | this.syncSource = other.syncSource; |
| 898 | this.authority = other.authority; |
| 899 | this.extras = new Bundle(other.extras); |
| 900 | this.delay = other.delay; |
| 901 | this.earliestRunTime = other.earliestRunTime; |
| 902 | this.key = toKey(); |
| 903 | } |
| 904 | |
| 905 | public void setDelay(long delay) { |
| 906 | this.delay = delay; |
| 907 | if (delay >= 0) { |
| 908 | this.earliestRunTime = SystemClock.elapsedRealtime() + delay; |
| 909 | } else { |
| 910 | this.earliestRunTime = 0; |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | public String toString() { |
| 915 | StringBuilder sb = new StringBuilder(); |
| 916 | sb.append("authority: ").append(authority); |
| 917 | sb.append(" account: ").append(account); |
| 918 | sb.append(" extras: "); |
| 919 | extrasToStringBuilder(extras, sb); |
| 920 | sb.append(" syncSource: ").append(syncSource); |
| 921 | sb.append(" when: ").append(earliestRunTime); |
| 922 | sb.append(" delay: ").append(delay); |
| 923 | sb.append(" key: {").append(key).append("}"); |
| 924 | if (rowId != null) sb.append(" rowId: ").append(rowId); |
| 925 | return sb.toString(); |
| 926 | } |
| 927 | |
| 928 | private String toKey() { |
| 929 | StringBuilder sb = new StringBuilder(); |
| 930 | sb.append("authority: ").append(authority); |
| 931 | sb.append(" account: ").append(account); |
| 932 | sb.append(" extras: "); |
| 933 | extrasToStringBuilder(extras, sb); |
| 934 | return sb.toString(); |
| 935 | } |
| 936 | |
| 937 | private static void extrasToStringBuilder(Bundle bundle, StringBuilder sb) { |
| 938 | sb.append("["); |
| 939 | for (String key : bundle.keySet()) { |
| 940 | sb.append(key).append("=").append(bundle.get(key)).append(" "); |
| 941 | } |
| 942 | sb.append("]"); |
| 943 | } |
| 944 | |
| 945 | public int compareTo(Object o) { |
| 946 | SyncOperation other = (SyncOperation)o; |
| 947 | if (earliestRunTime == other.earliestRunTime) { |
| 948 | return 0; |
| 949 | } |
| 950 | return (earliestRunTime < other.earliestRunTime) ? -1 : 1; |
| 951 | } |
| 952 | } |
| 953 | |
| 954 | /** |
| 955 | * @hide |
| 956 | */ |
| 957 | class ActiveSyncContext extends ISyncContext.Stub { |
| 958 | final SyncOperation mSyncOperation; |
| 959 | final long mHistoryRowId; |
| 960 | final IContentProvider mContentProvider; |
| 961 | final ISyncAdapter mSyncAdapter; |
| 962 | final long mStartTime; |
| 963 | long mTimeoutStartTime; |
| 964 | |
| 965 | public ActiveSyncContext(SyncOperation syncOperation, IContentProvider contentProvider, |
| 966 | ISyncAdapter syncAdapter, long historyRowId) { |
| 967 | super(); |
| 968 | mSyncOperation = syncOperation; |
| 969 | mHistoryRowId = historyRowId; |
| 970 | mContentProvider = contentProvider; |
| 971 | mSyncAdapter = syncAdapter; |
| 972 | mStartTime = SystemClock.elapsedRealtime(); |
| 973 | mTimeoutStartTime = mStartTime; |
| 974 | } |
| 975 | |
| 976 | public void sendHeartbeat() { |
| 977 | // ignore this call if it corresponds to an old sync session |
| 978 | if (mActiveSyncContext == this) { |
| 979 | SyncManager.this.updateHeartbeatTime(); |
| 980 | } |
| 981 | } |
| 982 | |
| 983 | public void onFinished(SyncResult result) { |
| 984 | // include "this" in the message so that the handler can ignore it if this |
| 985 | // ActiveSyncContext is no longer the mActiveSyncContext at message handling |
| 986 | // time |
| 987 | sendSyncFinishedOrCanceledMessage(this, result); |
| 988 | } |
| 989 | |
| 990 | public void toString(StringBuilder sb) { |
| 991 | sb.append("startTime ").append(mStartTime) |
| 992 | .append(", mTimeoutStartTime ").append(mTimeoutStartTime) |
| 993 | .append(", mHistoryRowId ").append(mHistoryRowId) |
| 994 | .append(", syncOperation ").append(mSyncOperation); |
| 995 | } |
| 996 | |
| 997 | @Override |
| 998 | public String toString() { |
| 999 | StringBuilder sb = new StringBuilder(); |
| 1000 | toString(sb); |
| 1001 | return sb.toString(); |
| 1002 | } |
| 1003 | } |
| 1004 | |
| 1005 | protected void dump(FileDescriptor fd, PrintWriter pw) { |
| 1006 | StringBuilder sb = new StringBuilder(); |
| 1007 | dumpSyncState(sb); |
| 1008 | sb.append("\n"); |
| 1009 | if (isSyncEnabled()) { |
| 1010 | dumpSyncHistory(sb); |
| 1011 | } |
| 1012 | pw.println(sb.toString()); |
| 1013 | } |
| 1014 | |
| 1015 | protected void dumpSyncState(StringBuilder sb) { |
| 1016 | sb.append("sync enabled: ").append(isSyncEnabled()).append("\n"); |
| 1017 | sb.append("data connected: ").append(mDataConnectionIsConnected).append("\n"); |
| 1018 | sb.append("memory low: ").append(mStorageIsLow).append("\n"); |
| 1019 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1020 | final Account[] accounts = mAccounts; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1021 | sb.append("accounts: "); |
| 1022 | if (accounts != null) { |
| 1023 | sb.append(accounts.length); |
| 1024 | } else { |
| 1025 | sb.append("none"); |
| 1026 | } |
| 1027 | sb.append("\n"); |
| 1028 | final long now = SystemClock.elapsedRealtime(); |
| 1029 | sb.append("now: ").append(now).append("\n"); |
| 1030 | sb.append("uptime: ").append(DateUtils.formatElapsedTime(now/1000)).append(" (HH:MM:SS)\n"); |
| 1031 | sb.append("time spent syncing : ") |
| 1032 | .append(DateUtils.formatElapsedTime( |
| 1033 | mSyncHandler.mSyncTimeTracker.timeSpentSyncing() / 1000)) |
| 1034 | .append(" (HH:MM:SS), sync ") |
| 1035 | .append(mSyncHandler.mSyncTimeTracker.mLastWasSyncing ? "" : "not ") |
| 1036 | .append("in progress").append("\n"); |
| 1037 | if (mSyncHandler.mAlarmScheduleTime != null) { |
| 1038 | sb.append("next alarm time: ").append(mSyncHandler.mAlarmScheduleTime) |
| 1039 | .append(" (") |
| 1040 | .append(DateUtils.formatElapsedTime((mSyncHandler.mAlarmScheduleTime-now)/1000)) |
| 1041 | .append(" (HH:MM:SS) from now)\n"); |
| 1042 | } else { |
| 1043 | sb.append("no alarm is scheduled (there had better not be any pending syncs)\n"); |
| 1044 | } |
| 1045 | |
| 1046 | sb.append("active sync: ").append(mActiveSyncContext).append("\n"); |
| 1047 | |
| 1048 | sb.append("notification info: "); |
| 1049 | mSyncHandler.mSyncNotificationInfo.toString(sb); |
| 1050 | sb.append("\n"); |
| 1051 | |
| 1052 | synchronized (mSyncQueue) { |
| 1053 | sb.append("sync queue: "); |
| 1054 | mSyncQueue.dump(sb); |
| 1055 | } |
| 1056 | |
| 1057 | Cursor c = mSyncStorageEngine.query(Sync.Active.CONTENT_URI, |
| 1058 | SYNC_ACTIVE_PROJECTION, null, null, null); |
| 1059 | sb.append("\n"); |
| 1060 | try { |
| 1061 | if (c.moveToNext()) { |
| 1062 | final long durationInSeconds = (now - c.getLong(2)) / 1000; |
| 1063 | sb.append("Active sync: ").append(c.getString(0)) |
| 1064 | .append(" ").append(c.getString(1)) |
| 1065 | .append(", duration is ") |
| 1066 | .append(DateUtils.formatElapsedTime(durationInSeconds)).append(".\n"); |
| 1067 | } else { |
| 1068 | sb.append("No sync is in progress.\n"); |
| 1069 | } |
| 1070 | } finally { |
| 1071 | c.close(); |
| 1072 | } |
| 1073 | |
| 1074 | c = mSyncStorageEngine.query(Sync.Pending.CONTENT_URI, |
| 1075 | SYNC_PENDING_PROJECTION, null, null, "account, authority"); |
| 1076 | sb.append("\nPending Syncs\n"); |
| 1077 | try { |
| 1078 | if (c.getCount() != 0) { |
| 1079 | dumpSyncPendingHeader(sb); |
| 1080 | while (c.moveToNext()) { |
| 1081 | dumpSyncPendingRow(sb, c); |
| 1082 | } |
| 1083 | dumpSyncPendingFooter(sb); |
| 1084 | } else { |
| 1085 | sb.append("none\n"); |
| 1086 | } |
| 1087 | } finally { |
| 1088 | c.close(); |
| 1089 | } |
| 1090 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1091 | Account currentAccount = null; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1092 | c = mSyncStorageEngine.query(Sync.Status.CONTENT_URI, |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1093 | STATUS_PROJECTION, null, null, "account_type, account, authority"); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1094 | sb.append("\nSync history by account and authority\n"); |
| 1095 | try { |
| 1096 | while (c.moveToNext()) { |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1097 | final Account account = new Account(c.getString(0), c.getString(13)); |
| 1098 | if (!account.equals(currentAccount)) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1099 | if (currentAccount != null) { |
| 1100 | dumpSyncHistoryFooter(sb); |
| 1101 | } |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1102 | currentAccount = account; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1103 | dumpSyncHistoryHeader(sb, currentAccount); |
| 1104 | } |
| 1105 | |
| 1106 | dumpSyncHistoryRow(sb, c); |
| 1107 | } |
| 1108 | if (c.getCount() > 0) dumpSyncHistoryFooter(sb); |
| 1109 | } finally { |
| 1110 | c.close(); |
| 1111 | } |
| 1112 | } |
| 1113 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1114 | private void dumpSyncHistoryHeader(StringBuilder sb, Account account) { |
| 1115 | sb.append(" ").append(account).append("\n"); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1116 | sb.append(" ___________________________________________________________________________________________________________________________\n"); |
| 1117 | sb.append(" | | num times synced | total | last success | |\n"); |
| 1118 | sb.append(" | authority | local | poll | server | user | total | duration | source | time | result if failing |\n"); |
| 1119 | } |
| 1120 | |
| 1121 | private static String[] STATUS_PROJECTION = new String[]{ |
| 1122 | Sync.Status.ACCOUNT, // 0 |
| 1123 | Sync.Status.AUTHORITY, // 1 |
| 1124 | Sync.Status.NUM_SYNCS, // 2 |
| 1125 | Sync.Status.TOTAL_ELAPSED_TIME, // 3 |
| 1126 | Sync.Status.NUM_SOURCE_LOCAL, // 4 |
| 1127 | Sync.Status.NUM_SOURCE_POLL, // 5 |
| 1128 | Sync.Status.NUM_SOURCE_SERVER, // 6 |
| 1129 | Sync.Status.NUM_SOURCE_USER, // 7 |
| 1130 | Sync.Status.LAST_SUCCESS_SOURCE, // 8 |
| 1131 | Sync.Status.LAST_SUCCESS_TIME, // 9 |
| 1132 | Sync.Status.LAST_FAILURE_SOURCE, // 10 |
| 1133 | Sync.Status.LAST_FAILURE_TIME, // 11 |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1134 | Sync.Status.LAST_FAILURE_MESG, // 12 |
| 1135 | Sync.Status.ACCOUNT_TYPE, // 13 |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1136 | }; |
| 1137 | |
| 1138 | private void dumpSyncHistoryRow(StringBuilder sb, Cursor c) { |
| 1139 | boolean hasSuccess = !c.isNull(9); |
| 1140 | boolean hasFailure = !c.isNull(11); |
| 1141 | Time timeSuccess = new Time(); |
| 1142 | if (hasSuccess) timeSuccess.set(c.getLong(9)); |
| 1143 | Time timeFailure = new Time(); |
| 1144 | if (hasFailure) timeFailure.set(c.getLong(11)); |
| 1145 | sb.append(String.format(" | %-15s | %5d | %5d | %6d | %5d | %5d | %8s | %7s | %19s | %19s |\n", |
| 1146 | c.getString(1), |
| 1147 | c.getLong(4), |
| 1148 | c.getLong(5), |
| 1149 | c.getLong(6), |
| 1150 | c.getLong(7), |
| 1151 | c.getLong(2), |
| 1152 | DateUtils.formatElapsedTime(c.getLong(3)/1000), |
| 1153 | hasSuccess ? Sync.History.SOURCES[c.getInt(8)] : "", |
| 1154 | hasSuccess ? timeSuccess.format("%Y-%m-%d %H:%M:%S") : "", |
| 1155 | hasFailure ? History.mesgToString(c.getString(12)) : "")); |
| 1156 | } |
| 1157 | |
| 1158 | private void dumpSyncHistoryFooter(StringBuilder sb) { |
| 1159 | sb.append(" |___________________________________________________________________________________________________________________________|\n"); |
| 1160 | } |
| 1161 | |
| 1162 | private void dumpSyncPendingHeader(StringBuilder sb) { |
| 1163 | sb.append(" ____________________________________________________\n"); |
| 1164 | sb.append(" | account | authority |\n"); |
| 1165 | } |
| 1166 | |
| 1167 | private void dumpSyncPendingRow(StringBuilder sb, Cursor c) { |
| 1168 | sb.append(String.format(" | %-30s | %-15s |\n", c.getString(0), c.getString(1))); |
| 1169 | } |
| 1170 | |
| 1171 | private void dumpSyncPendingFooter(StringBuilder sb) { |
| 1172 | sb.append(" |__________________________________________________|\n"); |
| 1173 | } |
| 1174 | |
| 1175 | protected void dumpSyncHistory(StringBuilder sb) { |
| 1176 | Cursor c = mSyncStorageEngine.query(Sync.History.CONTENT_URI, null, "event=?", |
| 1177 | new String[]{String.valueOf(Sync.History.EVENT_STOP)}, |
| 1178 | Sync.HistoryColumns.EVENT_TIME + " desc"); |
| 1179 | try { |
| 1180 | long numSyncsLastHour = 0, durationLastHour = 0; |
| 1181 | long numSyncsLastDay = 0, durationLastDay = 0; |
| 1182 | long numSyncsLastWeek = 0, durationLastWeek = 0; |
| 1183 | long numSyncsLast4Weeks = 0, durationLast4Weeks = 0; |
| 1184 | long numSyncsTotal = 0, durationTotal = 0; |
| 1185 | |
| 1186 | long now = System.currentTimeMillis(); |
| 1187 | int indexEventTime = c.getColumnIndexOrThrow(Sync.History.EVENT_TIME); |
| 1188 | int indexElapsedTime = c.getColumnIndexOrThrow(Sync.History.ELAPSED_TIME); |
| 1189 | while (c.moveToNext()) { |
| 1190 | long duration = c.getLong(indexElapsedTime); |
| 1191 | long endTime = c.getLong(indexEventTime) + duration; |
| 1192 | long millisSinceStart = now - endTime; |
| 1193 | numSyncsTotal++; |
| 1194 | durationTotal += duration; |
| 1195 | if (millisSinceStart < MILLIS_IN_HOUR) { |
| 1196 | numSyncsLastHour++; |
| 1197 | durationLastHour += duration; |
| 1198 | } |
| 1199 | if (millisSinceStart < MILLIS_IN_DAY) { |
| 1200 | numSyncsLastDay++; |
| 1201 | durationLastDay += duration; |
| 1202 | } |
| 1203 | if (millisSinceStart < MILLIS_IN_WEEK) { |
| 1204 | numSyncsLastWeek++; |
| 1205 | durationLastWeek += duration; |
| 1206 | } |
| 1207 | if (millisSinceStart < MILLIS_IN_4WEEKS) { |
| 1208 | numSyncsLast4Weeks++; |
| 1209 | durationLast4Weeks += duration; |
| 1210 | } |
| 1211 | } |
| 1212 | dumpSyncIntervalHeader(sb); |
| 1213 | dumpSyncInterval(sb, "hour", MILLIS_IN_HOUR, numSyncsLastHour, durationLastHour); |
| 1214 | dumpSyncInterval(sb, "day", MILLIS_IN_DAY, numSyncsLastDay, durationLastDay); |
| 1215 | dumpSyncInterval(sb, "week", MILLIS_IN_WEEK, numSyncsLastWeek, durationLastWeek); |
| 1216 | dumpSyncInterval(sb, "4 weeks", |
| 1217 | MILLIS_IN_4WEEKS, numSyncsLast4Weeks, durationLast4Weeks); |
| 1218 | dumpSyncInterval(sb, "total", 0, numSyncsTotal, durationTotal); |
| 1219 | dumpSyncIntervalFooter(sb); |
| 1220 | } finally { |
| 1221 | c.close(); |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | private void dumpSyncIntervalHeader(StringBuilder sb) { |
| 1226 | sb.append("Sync Stats\n"); |
| 1227 | sb.append(" ___________________________________________________________\n"); |
| 1228 | sb.append(" | | | duration in sec | |\n"); |
| 1229 | sb.append(" | interval | count | average | total | % of interval |\n"); |
| 1230 | } |
| 1231 | |
| 1232 | private void dumpSyncInterval(StringBuilder sb, String label, |
| 1233 | long interval, long numSyncs, long duration) { |
| 1234 | sb.append(String.format(" | %-8s | %6d | %8.1f | %8.1f", |
| 1235 | label, numSyncs, ((float)duration/numSyncs)/1000, (float)duration/1000)); |
| 1236 | if (interval > 0) { |
| 1237 | sb.append(String.format(" | %13.2f |\n", ((float)duration/interval)*100.0)); |
| 1238 | } else { |
| 1239 | sb.append(String.format(" | %13s |\n", "na")); |
| 1240 | } |
| 1241 | } |
| 1242 | |
| 1243 | private void dumpSyncIntervalFooter(StringBuilder sb) { |
| 1244 | sb.append(" |_________________________________________________________|\n"); |
| 1245 | } |
| 1246 | |
| 1247 | /** |
| 1248 | * A helper object to keep track of the time we have spent syncing since the last boot |
| 1249 | */ |
| 1250 | private class SyncTimeTracker { |
| 1251 | /** True if a sync was in progress on the most recent call to update() */ |
| 1252 | boolean mLastWasSyncing = false; |
| 1253 | /** Used to track when lastWasSyncing was last set */ |
| 1254 | long mWhenSyncStarted = 0; |
| 1255 | /** The cumulative time we have spent syncing */ |
| 1256 | private long mTimeSpentSyncing; |
| 1257 | |
| 1258 | /** Call to let the tracker know that the sync state may have changed */ |
| 1259 | public synchronized void update() { |
| 1260 | final boolean isSyncInProgress = mActiveSyncContext != null; |
| 1261 | if (isSyncInProgress == mLastWasSyncing) return; |
| 1262 | final long now = SystemClock.elapsedRealtime(); |
| 1263 | if (isSyncInProgress) { |
| 1264 | mWhenSyncStarted = now; |
| 1265 | } else { |
| 1266 | mTimeSpentSyncing += now - mWhenSyncStarted; |
| 1267 | } |
| 1268 | mLastWasSyncing = isSyncInProgress; |
| 1269 | } |
| 1270 | |
| 1271 | /** Get how long we have been syncing, in ms */ |
| 1272 | public synchronized long timeSpentSyncing() { |
| 1273 | if (!mLastWasSyncing) return mTimeSpentSyncing; |
| 1274 | |
| 1275 | final long now = SystemClock.elapsedRealtime(); |
| 1276 | return mTimeSpentSyncing + (now - mWhenSyncStarted); |
| 1277 | } |
| 1278 | } |
| 1279 | |
| 1280 | /** |
| 1281 | * Handles SyncOperation Messages that are posted to the associated |
| 1282 | * HandlerThread. |
| 1283 | */ |
| 1284 | class SyncHandler extends Handler { |
| 1285 | // Messages that can be sent on mHandler |
| 1286 | private static final int MESSAGE_SYNC_FINISHED = 1; |
| 1287 | private static final int MESSAGE_SYNC_ALARM = 2; |
| 1288 | private static final int MESSAGE_CHECK_ALARMS = 3; |
| 1289 | |
| 1290 | public final SyncNotificationInfo mSyncNotificationInfo = new SyncNotificationInfo(); |
| 1291 | private Long mAlarmScheduleTime = null; |
| 1292 | public final SyncTimeTracker mSyncTimeTracker = new SyncTimeTracker(); |
| 1293 | |
| 1294 | // used to track if we have installed the error notification so that we don't reinstall |
| 1295 | // it if sync is still failing |
| 1296 | private boolean mErrorNotificationInstalled = false; |
| 1297 | |
| 1298 | /** |
| 1299 | * Used to keep track of whether a sync notification is active and who it is for. |
| 1300 | */ |
| 1301 | class SyncNotificationInfo { |
| 1302 | // only valid if isActive is true |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1303 | public Account account; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1304 | |
| 1305 | // only valid if isActive is true |
| 1306 | public String authority; |
| 1307 | |
| 1308 | // true iff the notification manager has been asked to send the notification |
| 1309 | public boolean isActive = false; |
| 1310 | |
| 1311 | // Set when we transition from not running a sync to running a sync, and cleared on |
| 1312 | // the opposite transition. |
| 1313 | public Long startTime = null; |
| 1314 | |
| 1315 | public void toString(StringBuilder sb) { |
| 1316 | sb.append("account ").append(account) |
| 1317 | .append(", authority ").append(authority) |
| 1318 | .append(", isActive ").append(isActive) |
| 1319 | .append(", startTime ").append(startTime); |
| 1320 | } |
| 1321 | |
| 1322 | @Override |
| 1323 | public String toString() { |
| 1324 | StringBuilder sb = new StringBuilder(); |
| 1325 | toString(sb); |
| 1326 | return sb.toString(); |
| 1327 | } |
| 1328 | } |
| 1329 | |
| 1330 | public SyncHandler(Looper looper) { |
| 1331 | super(looper); |
| 1332 | } |
| 1333 | |
| 1334 | public void handleMessage(Message msg) { |
| 1335 | handleSyncHandlerMessage(msg); |
| 1336 | } |
| 1337 | |
| 1338 | private void handleSyncHandlerMessage(Message msg) { |
| 1339 | try { |
| 1340 | switch (msg.what) { |
| 1341 | case SyncHandler.MESSAGE_SYNC_FINISHED: |
| 1342 | if (Log.isLoggable(TAG, Log.VERBOSE)) { |
| 1343 | Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_FINISHED"); |
| 1344 | } |
| 1345 | SyncHandlerMessagePayload payload = (SyncHandlerMessagePayload)msg.obj; |
| 1346 | if (mActiveSyncContext != payload.activeSyncContext) { |
| 1347 | if (Config.LOGD) { |
| 1348 | Log.d(TAG, "handleSyncHandlerMessage: sync context doesn't match, " |
| 1349 | + "dropping: mActiveSyncContext " + mActiveSyncContext |
| 1350 | + " != " + payload.activeSyncContext); |
| 1351 | } |
| 1352 | return; |
| 1353 | } |
| 1354 | runSyncFinishedOrCanceled(payload.syncResult); |
| 1355 | |
| 1356 | // since we are no longer syncing, check if it is time to start a new sync |
| 1357 | runStateIdle(); |
| 1358 | break; |
| 1359 | |
| 1360 | case SyncHandler.MESSAGE_SYNC_ALARM: { |
| 1361 | boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE); |
| 1362 | if (isLoggable) { |
| 1363 | Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_ALARM"); |
| 1364 | } |
| 1365 | mAlarmScheduleTime = null; |
| 1366 | try { |
| 1367 | if (mActiveSyncContext != null) { |
| 1368 | if (isLoggable) { |
| 1369 | Log.v(TAG, "handleSyncHandlerMessage: sync context is active"); |
| 1370 | } |
| 1371 | runStateSyncing(); |
| 1372 | } |
| 1373 | |
| 1374 | // if the above call to runStateSyncing() resulted in the end of a sync, |
| 1375 | // check if it is time to start a new sync |
| 1376 | if (mActiveSyncContext == null) { |
| 1377 | if (isLoggable) { |
| 1378 | Log.v(TAG, "handleSyncHandlerMessage: " |
| 1379 | + "sync context is not active"); |
| 1380 | } |
| 1381 | runStateIdle(); |
| 1382 | } |
| 1383 | } finally { |
| 1384 | mHandleAlarmWakeLock.release(); |
| 1385 | } |
| 1386 | break; |
| 1387 | } |
| 1388 | |
| 1389 | case SyncHandler.MESSAGE_CHECK_ALARMS: |
| 1390 | if (Log.isLoggable(TAG, Log.VERBOSE)) { |
| 1391 | Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_CHECK_ALARMS"); |
| 1392 | } |
| 1393 | // we do all the work for this case in the finally block |
| 1394 | break; |
| 1395 | } |
| 1396 | } finally { |
| 1397 | final boolean isSyncInProgress = mActiveSyncContext != null; |
| 1398 | if (!isSyncInProgress) { |
| 1399 | mSyncWakeLock.release(); |
| 1400 | } |
| 1401 | manageSyncNotification(); |
| 1402 | manageErrorNotification(); |
| 1403 | manageSyncAlarm(); |
| 1404 | mSyncTimeTracker.update(); |
| 1405 | } |
| 1406 | } |
| 1407 | |
| 1408 | private void runStateSyncing() { |
| 1409 | // if the sync timeout has been reached then cancel it |
| 1410 | |
| 1411 | ActiveSyncContext activeSyncContext = mActiveSyncContext; |
| 1412 | |
| 1413 | final long now = SystemClock.elapsedRealtime(); |
| 1414 | if (now > activeSyncContext.mTimeoutStartTime + MAX_TIME_PER_SYNC) { |
| 1415 | SyncOperation nextSyncOperation; |
| 1416 | synchronized (mSyncQueue) { |
| 1417 | nextSyncOperation = mSyncQueue.head(); |
| 1418 | } |
| 1419 | if (nextSyncOperation != null && nextSyncOperation.earliestRunTime <= now) { |
| 1420 | if (Config.LOGD) { |
| 1421 | Log.d(TAG, "canceling and rescheduling sync because it ran too long: " |
| 1422 | + activeSyncContext.mSyncOperation); |
| 1423 | } |
| 1424 | rescheduleImmediately(activeSyncContext.mSyncOperation); |
| 1425 | sendSyncFinishedOrCanceledMessage(activeSyncContext, |
| 1426 | null /* no result since this is a cancel */); |
| 1427 | } else { |
| 1428 | activeSyncContext.mTimeoutStartTime = now + MAX_TIME_PER_SYNC; |
| 1429 | } |
| 1430 | } |
| 1431 | |
| 1432 | // no need to schedule an alarm, as that will be done by our caller. |
| 1433 | } |
| 1434 | |
| 1435 | private void runStateIdle() { |
| 1436 | boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE); |
| 1437 | if (isLoggable) Log.v(TAG, "runStateIdle"); |
| 1438 | |
| 1439 | // If we aren't ready to run (e.g. the data connection is down), get out. |
| 1440 | if (!mDataConnectionIsConnected) { |
| 1441 | if (isLoggable) { |
| 1442 | Log.v(TAG, "runStateIdle: no data connection, skipping"); |
| 1443 | } |
| 1444 | setStatusText("No data connection"); |
| 1445 | return; |
| 1446 | } |
| 1447 | |
| 1448 | if (mStorageIsLow) { |
| 1449 | if (isLoggable) { |
| 1450 | Log.v(TAG, "runStateIdle: memory low, skipping"); |
| 1451 | } |
| 1452 | setStatusText("Memory low"); |
| 1453 | return; |
| 1454 | } |
| 1455 | |
| 1456 | // If the accounts aren't known yet then we aren't ready to run. We will be kicked |
| 1457 | // when the account lookup request does complete. |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1458 | Account[] accounts = mAccounts; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1459 | if (accounts == null) { |
| 1460 | if (isLoggable) { |
| 1461 | Log.v(TAG, "runStateIdle: accounts not known, skipping"); |
| 1462 | } |
| 1463 | setStatusText("Accounts not known yet"); |
| 1464 | return; |
| 1465 | } |
| 1466 | |
| 1467 | // Otherwise consume SyncOperations from the head of the SyncQueue until one is |
| 1468 | // found that is runnable (not disabled, etc). If that one is ready to run then |
| 1469 | // start it, otherwise just get out. |
| 1470 | SyncOperation syncOperation; |
| 1471 | final Sync.Settings.QueryMap syncSettings = getSyncSettings(); |
| 1472 | final ConnectivityManager connManager = (ConnectivityManager) |
| 1473 | mContext.getSystemService(Context.CONNECTIVITY_SERVICE); |
| 1474 | final boolean backgroundDataSetting = connManager.getBackgroundDataSetting(); |
| 1475 | synchronized (mSyncQueue) { |
| 1476 | while (true) { |
| 1477 | syncOperation = mSyncQueue.head(); |
| 1478 | if (syncOperation == null) { |
| 1479 | if (isLoggable) { |
| 1480 | Log.v(TAG, "runStateIdle: no more sync operations, returning"); |
| 1481 | } |
| 1482 | return; |
| 1483 | } |
| 1484 | |
| 1485 | // Sync is disabled, drop this operation. |
| 1486 | if (!isSyncEnabled()) { |
| 1487 | if (isLoggable) { |
| 1488 | Log.v(TAG, "runStateIdle: sync disabled, dropping " + syncOperation); |
| 1489 | } |
| 1490 | mSyncQueue.popHead(); |
| 1491 | continue; |
| 1492 | } |
| 1493 | |
| 1494 | // skip the sync if it isn't a force and the settings are off for this provider |
| 1495 | final boolean force = syncOperation.extras.getBoolean( |
| 1496 | ContentResolver.SYNC_EXTRAS_FORCE, false); |
| 1497 | if (!force && (!backgroundDataSetting |
| 1498 | || !syncSettings.getListenForNetworkTickles() |
| 1499 | || !syncSettings.getSyncProviderAutomatically( |
| 1500 | syncOperation.authority))) { |
| 1501 | if (isLoggable) { |
| 1502 | Log.v(TAG, "runStateIdle: sync off, dropping " + syncOperation); |
| 1503 | } |
| 1504 | mSyncQueue.popHead(); |
| 1505 | continue; |
| 1506 | } |
| 1507 | |
| 1508 | // skip the sync if the account of this operation no longer exists |
| 1509 | if (!ArrayUtils.contains(accounts, syncOperation.account)) { |
| 1510 | mSyncQueue.popHead(); |
| 1511 | if (isLoggable) { |
| 1512 | Log.v(TAG, "runStateIdle: account not present, dropping " |
| 1513 | + syncOperation); |
| 1514 | } |
| 1515 | continue; |
| 1516 | } |
| 1517 | |
| 1518 | // go ahead and try to sync this syncOperation |
| 1519 | if (isLoggable) { |
| 1520 | Log.v(TAG, "runStateIdle: found sync candidate: " + syncOperation); |
| 1521 | } |
| 1522 | break; |
| 1523 | } |
| 1524 | |
| 1525 | // If the first SyncOperation isn't ready to run schedule a wakeup and |
| 1526 | // get out. |
| 1527 | final long now = SystemClock.elapsedRealtime(); |
| 1528 | if (syncOperation.earliestRunTime > now) { |
| 1529 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 1530 | Log.d(TAG, "runStateIdle: the time is " + now + " yet the next " |
| 1531 | + "sync operation is for " + syncOperation.earliestRunTime |
| 1532 | + ": " + syncOperation); |
| 1533 | } |
| 1534 | return; |
| 1535 | } |
| 1536 | |
| 1537 | // We will do this sync. Remove it from the queue and run it outside of the |
| 1538 | // synchronized block. |
| 1539 | if (isLoggable) { |
| 1540 | Log.v(TAG, "runStateIdle: we are going to sync " + syncOperation); |
| 1541 | } |
| 1542 | mSyncQueue.popHead(); |
| 1543 | } |
| 1544 | |
| 1545 | String providerName = syncOperation.authority; |
| 1546 | ensureContentResolver(); |
| 1547 | IContentProvider contentProvider; |
| 1548 | |
| 1549 | // acquire the provider and update the sync history |
| 1550 | try { |
| 1551 | contentProvider = mContentResolver.acquireProvider(providerName); |
| 1552 | if (contentProvider == null) { |
| 1553 | Log.e(TAG, "Provider " + providerName + " doesn't exist"); |
| 1554 | return; |
| 1555 | } |
| 1556 | if (contentProvider.getSyncAdapter() == null) { |
| 1557 | Log.e(TAG, "Provider " + providerName + " isn't syncable, " + contentProvider); |
| 1558 | return; |
| 1559 | } |
| 1560 | } catch (RemoteException remoteExc) { |
| 1561 | Log.e(TAG, "Caught a RemoteException while preparing for sync, rescheduling " |
| 1562 | + syncOperation, remoteExc); |
| 1563 | rescheduleWithDelay(syncOperation); |
| 1564 | return; |
| 1565 | } catch (RuntimeException exc) { |
| 1566 | Log.e(TAG, "Caught a RuntimeException while validating sync of " + providerName, |
| 1567 | exc); |
| 1568 | return; |
| 1569 | } |
| 1570 | |
| 1571 | final long historyRowId = insertStartSyncEvent(syncOperation); |
| 1572 | |
| 1573 | try { |
| 1574 | ISyncAdapter syncAdapter = contentProvider.getSyncAdapter(); |
| 1575 | ActiveSyncContext activeSyncContext = new ActiveSyncContext(syncOperation, |
| 1576 | contentProvider, syncAdapter, historyRowId); |
| 1577 | mSyncWakeLock.acquire(); |
| 1578 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 1579 | Log.d(TAG, "starting sync of " + syncOperation); |
| 1580 | } |
| 1581 | syncAdapter.startSync(activeSyncContext, syncOperation.account, |
| 1582 | syncOperation.extras); |
| 1583 | mActiveSyncContext = activeSyncContext; |
| 1584 | mSyncStorageEngine.setActiveSync(mActiveSyncContext); |
| 1585 | } catch (RemoteException remoteExc) { |
| 1586 | if (Config.LOGD) { |
| 1587 | Log.d(TAG, "runStateIdle: caught a RemoteException, rescheduling", remoteExc); |
| 1588 | } |
| 1589 | mActiveSyncContext = null; |
| 1590 | mSyncStorageEngine.setActiveSync(mActiveSyncContext); |
| 1591 | rescheduleWithDelay(syncOperation); |
| 1592 | } catch (RuntimeException exc) { |
| 1593 | mActiveSyncContext = null; |
| 1594 | mSyncStorageEngine.setActiveSync(mActiveSyncContext); |
| 1595 | Log.e(TAG, "Caught a RuntimeException while starting the sync " + syncOperation, |
| 1596 | exc); |
| 1597 | } |
| 1598 | |
| 1599 | // no need to schedule an alarm, as that will be done by our caller. |
| 1600 | } |
| 1601 | |
| 1602 | private void runSyncFinishedOrCanceled(SyncResult syncResult) { |
| 1603 | boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE); |
| 1604 | if (isLoggable) Log.v(TAG, "runSyncFinishedOrCanceled"); |
| 1605 | ActiveSyncContext activeSyncContext = mActiveSyncContext; |
| 1606 | mActiveSyncContext = null; |
| 1607 | mSyncStorageEngine.setActiveSync(mActiveSyncContext); |
| 1608 | |
| 1609 | final SyncOperation syncOperation = activeSyncContext.mSyncOperation; |
| 1610 | |
| 1611 | final long elapsedTime = SystemClock.elapsedRealtime() - activeSyncContext.mStartTime; |
| 1612 | |
| 1613 | String historyMessage; |
| 1614 | int downstreamActivity; |
| 1615 | int upstreamActivity; |
| 1616 | if (syncResult != null) { |
| 1617 | if (isLoggable) { |
| 1618 | Log.v(TAG, "runSyncFinishedOrCanceled: is a finished: operation " |
| 1619 | + syncOperation + ", result " + syncResult); |
| 1620 | } |
| 1621 | |
| 1622 | if (!syncResult.hasError()) { |
| 1623 | if (isLoggable) { |
| 1624 | Log.v(TAG, "finished sync operation " + syncOperation); |
| 1625 | } |
| 1626 | historyMessage = History.MESG_SUCCESS; |
| 1627 | // TODO: set these correctly when the SyncResult is extended to include it |
| 1628 | downstreamActivity = 0; |
| 1629 | upstreamActivity = 0; |
| 1630 | } else { |
| 1631 | maybeRescheduleSync(syncResult, syncOperation); |
| 1632 | if (Config.LOGD) { |
| 1633 | Log.d(TAG, "failed sync operation " + syncOperation); |
| 1634 | } |
| 1635 | historyMessage = Integer.toString(syncResultToErrorNumber(syncResult)); |
| 1636 | // TODO: set these correctly when the SyncResult is extended to include it |
| 1637 | downstreamActivity = 0; |
| 1638 | upstreamActivity = 0; |
| 1639 | } |
| 1640 | } else { |
| 1641 | if (isLoggable) { |
| 1642 | Log.v(TAG, "runSyncFinishedOrCanceled: is a cancel: operation " |
| 1643 | + syncOperation); |
| 1644 | } |
| 1645 | try { |
| 1646 | activeSyncContext.mSyncAdapter.cancelSync(); |
| 1647 | } catch (RemoteException e) { |
| 1648 | // we don't need to retry this in this case |
| 1649 | } |
| 1650 | historyMessage = History.MESG_CANCELED; |
| 1651 | downstreamActivity = 0; |
| 1652 | upstreamActivity = 0; |
| 1653 | } |
| 1654 | |
| 1655 | stopSyncEvent(activeSyncContext.mHistoryRowId, syncOperation, historyMessage, |
| 1656 | upstreamActivity, downstreamActivity, elapsedTime); |
| 1657 | |
| 1658 | mContentResolver.releaseProvider(activeSyncContext.mContentProvider); |
| 1659 | |
| 1660 | if (syncResult != null && syncResult.tooManyDeletions) { |
| 1661 | installHandleTooManyDeletesNotification(syncOperation.account, |
| 1662 | syncOperation.authority, syncResult.stats.numDeletes); |
| 1663 | } else { |
| 1664 | mNotificationMgr.cancel( |
| 1665 | syncOperation.account.hashCode() ^ syncOperation.authority.hashCode()); |
| 1666 | } |
| 1667 | |
| 1668 | if (syncResult != null && syncResult.fullSyncRequested) { |
| 1669 | scheduleSyncOperation(new SyncOperation(syncOperation.account, |
| 1670 | syncOperation.syncSource, syncOperation.authority, new Bundle(), 0)); |
| 1671 | } |
| 1672 | // no need to schedule an alarm, as that will be done by our caller. |
| 1673 | } |
| 1674 | |
| 1675 | /** |
| 1676 | * Convert the error-containing SyncResult into the Sync.History error number. Since |
| 1677 | * the SyncResult may indicate multiple errors at once, this method just returns the |
| 1678 | * most "serious" error. |
| 1679 | * @param syncResult the SyncResult from which to read |
| 1680 | * @return the most "serious" error set in the SyncResult |
| 1681 | * @throws IllegalStateException if the SyncResult does not indicate any errors. |
| 1682 | * If SyncResult.error() is true then it is safe to call this. |
| 1683 | */ |
| 1684 | private int syncResultToErrorNumber(SyncResult syncResult) { |
| 1685 | if (syncResult.syncAlreadyInProgress) return History.ERROR_SYNC_ALREADY_IN_PROGRESS; |
| 1686 | if (syncResult.stats.numAuthExceptions > 0) return History.ERROR_AUTHENTICATION; |
| 1687 | if (syncResult.stats.numIoExceptions > 0) return History.ERROR_IO; |
| 1688 | if (syncResult.stats.numParseExceptions > 0) return History.ERROR_PARSE; |
| 1689 | if (syncResult.stats.numConflictDetectedExceptions > 0) return History.ERROR_CONFLICT; |
| 1690 | if (syncResult.tooManyDeletions) return History.ERROR_TOO_MANY_DELETIONS; |
| 1691 | if (syncResult.tooManyRetries) return History.ERROR_TOO_MANY_RETRIES; |
| 1692 | if (syncResult.databaseError) return History.ERROR_INTERNAL; |
| 1693 | throw new IllegalStateException("we are not in an error state, " + syncResult); |
| 1694 | } |
| 1695 | |
| 1696 | private void manageSyncNotification() { |
| 1697 | boolean shouldCancel; |
| 1698 | boolean shouldInstall; |
| 1699 | |
| 1700 | if (mActiveSyncContext == null) { |
| 1701 | mSyncNotificationInfo.startTime = null; |
| 1702 | |
| 1703 | // we aren't syncing. if the notification is active then remember that we need |
| 1704 | // to cancel it and then clear out the info |
| 1705 | shouldCancel = mSyncNotificationInfo.isActive; |
| 1706 | shouldInstall = false; |
| 1707 | } else { |
| 1708 | // we are syncing |
| 1709 | final SyncOperation syncOperation = mActiveSyncContext.mSyncOperation; |
| 1710 | |
| 1711 | final long now = SystemClock.elapsedRealtime(); |
| 1712 | if (mSyncNotificationInfo.startTime == null) { |
| 1713 | mSyncNotificationInfo.startTime = now; |
| 1714 | } |
| 1715 | |
| 1716 | // cancel the notification if it is up and the authority or account is wrong |
| 1717 | shouldCancel = mSyncNotificationInfo.isActive && |
| 1718 | (!syncOperation.authority.equals(mSyncNotificationInfo.authority) |
| 1719 | || !syncOperation.account.equals(mSyncNotificationInfo.account)); |
| 1720 | |
| 1721 | // there are four cases: |
| 1722 | // - the notification is up and there is no change: do nothing |
| 1723 | // - the notification is up but we should cancel since it is stale: |
| 1724 | // need to install |
| 1725 | // - the notification is not up but it isn't time yet: don't install |
| 1726 | // - the notification is not up and it is time: need to install |
| 1727 | |
| 1728 | if (mSyncNotificationInfo.isActive) { |
| 1729 | shouldInstall = shouldCancel; |
| 1730 | } else { |
| 1731 | final boolean timeToShowNotification = |
| 1732 | now > mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY; |
| 1733 | final boolean syncIsForced = syncOperation.extras |
| 1734 | .getBoolean(ContentResolver.SYNC_EXTRAS_FORCE, false); |
| 1735 | shouldInstall = timeToShowNotification || syncIsForced; |
| 1736 | } |
| 1737 | } |
| 1738 | |
| 1739 | if (shouldCancel && !shouldInstall) { |
| 1740 | mNeedSyncActiveNotification = false; |
| 1741 | sendSyncStateIntent(); |
| 1742 | mSyncNotificationInfo.isActive = false; |
| 1743 | } |
| 1744 | |
| 1745 | if (shouldInstall) { |
| 1746 | SyncOperation syncOperation = mActiveSyncContext.mSyncOperation; |
| 1747 | mNeedSyncActiveNotification = true; |
| 1748 | sendSyncStateIntent(); |
| 1749 | mSyncNotificationInfo.isActive = true; |
| 1750 | mSyncNotificationInfo.account = syncOperation.account; |
| 1751 | mSyncNotificationInfo.authority = syncOperation.authority; |
| 1752 | } |
| 1753 | } |
| 1754 | |
| 1755 | /** |
| 1756 | * Check if there were any long-lasting errors, if so install the error notification, |
| 1757 | * otherwise cancel the error notification. |
| 1758 | */ |
| 1759 | private void manageErrorNotification() { |
| 1760 | // |
| 1761 | long when = mSyncStorageEngine.getInitialSyncFailureTime(); |
| 1762 | if ((when > 0) && (when + ERROR_NOTIFICATION_DELAY_MS < System.currentTimeMillis())) { |
| 1763 | if (!mErrorNotificationInstalled) { |
| 1764 | mNeedSyncErrorNotification = true; |
| 1765 | sendSyncStateIntent(); |
| 1766 | } |
| 1767 | mErrorNotificationInstalled = true; |
| 1768 | } else { |
| 1769 | if (mErrorNotificationInstalled) { |
| 1770 | mNeedSyncErrorNotification = false; |
| 1771 | sendSyncStateIntent(); |
| 1772 | } |
| 1773 | mErrorNotificationInstalled = false; |
| 1774 | } |
| 1775 | } |
| 1776 | |
| 1777 | private void manageSyncAlarm() { |
| 1778 | // in each of these cases the sync loop will be kicked, which will cause this |
| 1779 | // method to be called again |
| 1780 | if (!mDataConnectionIsConnected) return; |
| 1781 | if (mAccounts == null) return; |
| 1782 | if (mStorageIsLow) return; |
| 1783 | |
| 1784 | // Compute the alarm fire time: |
| 1785 | // - not syncing: time of the next sync operation |
| 1786 | // - syncing, no notification: time from sync start to notification create time |
| 1787 | // - syncing, with notification: time till timeout of the active sync operation |
| 1788 | Long alarmTime = null; |
| 1789 | ActiveSyncContext activeSyncContext = mActiveSyncContext; |
| 1790 | if (activeSyncContext == null) { |
| 1791 | SyncOperation syncOperation; |
| 1792 | synchronized (mSyncQueue) { |
| 1793 | syncOperation = mSyncQueue.head(); |
| 1794 | } |
| 1795 | if (syncOperation != null) { |
| 1796 | alarmTime = syncOperation.earliestRunTime; |
| 1797 | } |
| 1798 | } else { |
| 1799 | final long notificationTime = |
| 1800 | mSyncHandler.mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY; |
| 1801 | final long timeoutTime = |
| 1802 | mActiveSyncContext.mTimeoutStartTime + MAX_TIME_PER_SYNC; |
| 1803 | if (mSyncHandler.mSyncNotificationInfo.isActive) { |
| 1804 | alarmTime = timeoutTime; |
| 1805 | } else { |
| 1806 | alarmTime = Math.min(notificationTime, timeoutTime); |
| 1807 | } |
| 1808 | } |
| 1809 | |
| 1810 | // adjust the alarmTime so that we will wake up when it is time to |
| 1811 | // install the error notification |
| 1812 | if (!mErrorNotificationInstalled) { |
| 1813 | long when = mSyncStorageEngine.getInitialSyncFailureTime(); |
| 1814 | if (when > 0) { |
| 1815 | when += ERROR_NOTIFICATION_DELAY_MS; |
| 1816 | // convert when fron absolute time to elapsed run time |
| 1817 | long delay = when - System.currentTimeMillis(); |
| 1818 | when = SystemClock.elapsedRealtime() + delay; |
| 1819 | alarmTime = alarmTime != null ? Math.min(alarmTime, when) : when; |
| 1820 | } |
| 1821 | } |
| 1822 | |
| 1823 | // determine if we need to set or cancel the alarm |
| 1824 | boolean shouldSet = false; |
| 1825 | boolean shouldCancel = false; |
| 1826 | final boolean alarmIsActive = mAlarmScheduleTime != null; |
| 1827 | final boolean needAlarm = alarmTime != null; |
| 1828 | if (needAlarm) { |
| 1829 | if (!alarmIsActive || alarmTime < mAlarmScheduleTime) { |
| 1830 | shouldSet = true; |
| 1831 | } |
| 1832 | } else { |
| 1833 | shouldCancel = alarmIsActive; |
| 1834 | } |
| 1835 | |
| 1836 | // set or cancel the alarm as directed |
| 1837 | ensureAlarmService(); |
| 1838 | if (shouldSet) { |
| 1839 | mAlarmScheduleTime = alarmTime; |
| 1840 | mAlarmService.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, |
| 1841 | mSyncAlarmIntent); |
| 1842 | } else if (shouldCancel) { |
| 1843 | mAlarmScheduleTime = null; |
| 1844 | mAlarmService.cancel(mSyncAlarmIntent); |
| 1845 | } |
| 1846 | } |
| 1847 | |
| 1848 | private void sendSyncStateIntent() { |
| 1849 | Intent syncStateIntent = new Intent(Intent.ACTION_SYNC_STATE_CHANGED); |
| 1850 | syncStateIntent.putExtra("active", mNeedSyncActiveNotification); |
| 1851 | syncStateIntent.putExtra("failing", mNeedSyncErrorNotification); |
| 1852 | mContext.sendBroadcast(syncStateIntent); |
| 1853 | } |
| 1854 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1855 | private void installHandleTooManyDeletesNotification(Account account, String authority, |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1856 | long numDeletes) { |
| 1857 | if (mNotificationMgr == null) return; |
| 1858 | Intent clickIntent = new Intent(); |
| 1859 | clickIntent.setClassName("com.android.providers.subscribedfeeds", |
| 1860 | "com.android.settings.SyncActivityTooManyDeletes"); |
| 1861 | clickIntent.putExtra("account", account); |
| 1862 | clickIntent.putExtra("provider", authority); |
| 1863 | clickIntent.putExtra("numDeletes", numDeletes); |
| 1864 | |
| 1865 | if (!isActivityAvailable(clickIntent)) { |
| 1866 | Log.w(TAG, "No activity found to handle too many deletes."); |
| 1867 | return; |
| 1868 | } |
| 1869 | |
| 1870 | final PendingIntent pendingIntent = PendingIntent |
| 1871 | .getActivity(mContext, 0, clickIntent, PendingIntent.FLAG_CANCEL_CURRENT); |
| 1872 | |
| 1873 | CharSequence tooManyDeletesDescFormat = mContext.getResources().getText( |
| 1874 | R.string.contentServiceTooManyDeletesNotificationDesc); |
| 1875 | |
| 1876 | String[] authorities = authority.split(";"); |
| 1877 | Notification notification = |
| 1878 | new Notification(R.drawable.stat_notify_sync_error, |
| 1879 | mContext.getString(R.string.contentServiceSync), |
| 1880 | System.currentTimeMillis()); |
| 1881 | notification.setLatestEventInfo(mContext, |
| 1882 | mContext.getString(R.string.contentServiceSyncNotificationTitle), |
| 1883 | String.format(tooManyDeletesDescFormat.toString(), authorities[0]), |
| 1884 | pendingIntent); |
| 1885 | notification.flags |= Notification.FLAG_ONGOING_EVENT; |
| 1886 | mNotificationMgr.notify(account.hashCode() ^ authority.hashCode(), notification); |
| 1887 | } |
| 1888 | |
| 1889 | /** |
| 1890 | * Checks whether an activity exists on the system image for the given intent. |
| 1891 | * |
| 1892 | * @param intent The intent for an activity. |
| 1893 | * @return Whether or not an activity exists. |
| 1894 | */ |
| 1895 | private boolean isActivityAvailable(Intent intent) { |
| 1896 | PackageManager pm = mContext.getPackageManager(); |
| 1897 | List<ResolveInfo> list = pm.queryIntentActivities(intent, 0); |
| 1898 | int listSize = list.size(); |
| 1899 | for (int i = 0; i < listSize; i++) { |
| 1900 | ResolveInfo resolveInfo = list.get(i); |
| 1901 | if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) |
| 1902 | != 0) { |
| 1903 | return true; |
| 1904 | } |
| 1905 | } |
| 1906 | |
| 1907 | return false; |
| 1908 | } |
| 1909 | |
| 1910 | public long insertStartSyncEvent(SyncOperation syncOperation) { |
| 1911 | final int source = syncOperation.syncSource; |
| 1912 | final long now = System.currentTimeMillis(); |
| 1913 | |
| 1914 | EventLog.writeEvent(2720, syncOperation.authority, Sync.History.EVENT_START, source); |
| 1915 | |
| 1916 | return mSyncStorageEngine.insertStartSyncEvent( |
| 1917 | syncOperation.account, syncOperation.authority, now, source); |
| 1918 | } |
| 1919 | |
| 1920 | public void stopSyncEvent(long rowId, SyncOperation syncOperation, String resultMessage, |
| 1921 | int upstreamActivity, int downstreamActivity, long elapsedTime) { |
| 1922 | EventLog.writeEvent(2720, syncOperation.authority, Sync.History.EVENT_STOP, syncOperation.syncSource); |
| 1923 | |
| 1924 | mSyncStorageEngine.stopSyncEvent(rowId, elapsedTime, resultMessage, |
| 1925 | downstreamActivity, upstreamActivity); |
| 1926 | } |
| 1927 | } |
| 1928 | |
| 1929 | static class SyncQueue { |
| 1930 | private SyncStorageEngine mSyncStorageEngine; |
| 1931 | private final String[] COLUMNS = new String[]{ |
| 1932 | "_id", |
| 1933 | "authority", |
| 1934 | "account", |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1935 | "account_type", |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1936 | "extras", |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1937 | "source", |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1938 | }; |
| 1939 | private static final int COLUMN_ID = 0; |
| 1940 | private static final int COLUMN_AUTHORITY = 1; |
| 1941 | private static final int COLUMN_ACCOUNT = 2; |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 1942 | private static final int COLUMN_ACCOUNT_TYPE = 3; |
| 1943 | private static final int COLUMN_EXTRAS = 4; |
| 1944 | private static final int COLUMN_SOURCE = 5; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1945 | |
| 1946 | private static final boolean DEBUG_CHECK_DATA_CONSISTENCY = false; |
| 1947 | |
| 1948 | // A priority queue of scheduled SyncOperations that is designed to make it quick |
| 1949 | // to find the next SyncOperation that should be considered for running. |
| 1950 | private final PriorityQueue<SyncOperation> mOpsByWhen = new PriorityQueue<SyncOperation>(); |
| 1951 | |
| 1952 | // A Map of SyncOperations operationKey -> SyncOperation that is designed for |
| 1953 | // quick lookup of an enqueued SyncOperation. |
| 1954 | private final HashMap<String, SyncOperation> mOpsByKey = Maps.newHashMap(); |
| 1955 | |
| 1956 | public SyncQueue(SyncStorageEngine syncStorageEngine) { |
| 1957 | mSyncStorageEngine = syncStorageEngine; |
| 1958 | Cursor cursor = mSyncStorageEngine.getPendingSyncsCursor(COLUMNS); |
| 1959 | try { |
| 1960 | while (cursor.moveToNext()) { |
| 1961 | add(cursorToOperation(cursor), |
| 1962 | true /* this is being added from the database */); |
| 1963 | } |
| 1964 | } finally { |
| 1965 | cursor.close(); |
| 1966 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */); |
| 1967 | } |
| 1968 | } |
| 1969 | |
| 1970 | public boolean add(SyncOperation operation) { |
| 1971 | return add(new SyncOperation(operation), |
| 1972 | false /* this is not coming from the database */); |
| 1973 | } |
| 1974 | |
| 1975 | private boolean add(SyncOperation operation, boolean fromDatabase) { |
| 1976 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(!fromDatabase); |
| 1977 | |
| 1978 | // If this operation is expedited then set its earliestRunTime to be immediately |
| 1979 | // before the head of the list, or not if none are in the list. |
| 1980 | if (operation.delay < 0) { |
| 1981 | SyncOperation headOperation = head(); |
| 1982 | if (headOperation != null) { |
| 1983 | operation.earliestRunTime = Math.min(SystemClock.elapsedRealtime(), |
| 1984 | headOperation.earliestRunTime - 1); |
| 1985 | } else { |
| 1986 | operation.earliestRunTime = SystemClock.elapsedRealtime(); |
| 1987 | } |
| 1988 | } |
| 1989 | |
| 1990 | // - if an operation with the same key exists and this one should run earlier, |
| 1991 | // delete the old one and add the new one |
| 1992 | // - if an operation with the same key exists and if this one should run |
| 1993 | // later, ignore it |
| 1994 | // - if no operation exists then add the new one |
| 1995 | final String operationKey = operation.key; |
| 1996 | SyncOperation existingOperation = mOpsByKey.get(operationKey); |
| 1997 | |
| 1998 | // if this operation matches an existing operation that is being retried (delay > 0) |
| 1999 | // and this operation isn't forced, ignore this operation |
| 2000 | if (existingOperation != null && existingOperation.delay > 0) { |
| 2001 | if (!operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_FORCE, false)) { |
| 2002 | return false; |
| 2003 | } |
| 2004 | } |
| 2005 | |
| 2006 | if (existingOperation != null |
| 2007 | && operation.earliestRunTime >= existingOperation.earliestRunTime) { |
| 2008 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(!fromDatabase); |
| 2009 | return false; |
| 2010 | } |
| 2011 | |
| 2012 | if (existingOperation != null) { |
| 2013 | removeByKey(operationKey); |
| 2014 | } |
| 2015 | |
| 2016 | if (operation.rowId == null) { |
| 2017 | byte[] extrasData = null; |
| 2018 | Parcel parcel = Parcel.obtain(); |
| 2019 | try { |
| 2020 | operation.extras.writeToParcel(parcel, 0); |
| 2021 | extrasData = parcel.marshall(); |
| 2022 | } finally { |
| 2023 | parcel.recycle(); |
| 2024 | } |
| 2025 | ContentValues values = new ContentValues(); |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 2026 | values.put("account", operation.account.mName); |
| 2027 | values.put("account_type", operation.account.mType); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 2028 | values.put("authority", operation.authority); |
| 2029 | values.put("source", operation.syncSource); |
| 2030 | values.put("extras", extrasData); |
| 2031 | Uri pendingUri = mSyncStorageEngine.insertIntoPending(values); |
| 2032 | operation.rowId = pendingUri == null ? null : ContentUris.parseId(pendingUri); |
| 2033 | if (operation.rowId == null) { |
| 2034 | throw new IllegalStateException("error adding pending sync operation " |
| 2035 | + operation); |
| 2036 | } |
| 2037 | } |
| 2038 | |
| 2039 | if (DEBUG_CHECK_DATA_CONSISTENCY) { |
| 2040 | debugCheckDataStructures( |
| 2041 | false /* don't compare with the DB, since we know |
| 2042 | it is inconsistent right now */ ); |
| 2043 | } |
| 2044 | mOpsByKey.put(operationKey, operation); |
| 2045 | mOpsByWhen.add(operation); |
| 2046 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(!fromDatabase); |
| 2047 | return true; |
| 2048 | } |
| 2049 | |
| 2050 | public void removeByKey(String operationKey) { |
| 2051 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */); |
| 2052 | SyncOperation operationToRemove = mOpsByKey.remove(operationKey); |
| 2053 | if (!mOpsByWhen.remove(operationToRemove)) { |
| 2054 | throw new IllegalStateException( |
| 2055 | "unable to find " + operationToRemove + " in mOpsByWhen"); |
| 2056 | } |
| 2057 | |
| 2058 | if (mSyncStorageEngine.deleteFromPending(operationToRemove.rowId) != 1) { |
| 2059 | throw new IllegalStateException("unable to find pending row for " |
| 2060 | + operationToRemove); |
| 2061 | } |
| 2062 | |
| 2063 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */); |
| 2064 | } |
| 2065 | |
| 2066 | public SyncOperation head() { |
| 2067 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */); |
| 2068 | return mOpsByWhen.peek(); |
| 2069 | } |
| 2070 | |
| 2071 | public void popHead() { |
| 2072 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */); |
| 2073 | SyncOperation operation = mOpsByWhen.remove(); |
| 2074 | if (mOpsByKey.remove(operation.key) == null) { |
| 2075 | throw new IllegalStateException("unable to find " + operation + " in mOpsByKey"); |
| 2076 | } |
| 2077 | |
| 2078 | if (mSyncStorageEngine.deleteFromPending(operation.rowId) != 1) { |
| 2079 | throw new IllegalStateException("unable to find pending row for " + operation); |
| 2080 | } |
| 2081 | |
| 2082 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */); |
| 2083 | } |
| 2084 | |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 2085 | public void clear(Account account, String authority) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 2086 | Iterator<Map.Entry<String, SyncOperation>> entries = mOpsByKey.entrySet().iterator(); |
| 2087 | while (entries.hasNext()) { |
| 2088 | Map.Entry<String, SyncOperation> entry = entries.next(); |
| 2089 | SyncOperation syncOperation = entry.getValue(); |
| 2090 | if (account != null && !syncOperation.account.equals(account)) continue; |
| 2091 | if (authority != null && !syncOperation.authority.equals(authority)) continue; |
| 2092 | |
| 2093 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */); |
| 2094 | entries.remove(); |
| 2095 | if (!mOpsByWhen.remove(syncOperation)) { |
| 2096 | throw new IllegalStateException( |
| 2097 | "unable to find " + syncOperation + " in mOpsByWhen"); |
| 2098 | } |
| 2099 | |
| 2100 | if (mSyncStorageEngine.deleteFromPending(syncOperation.rowId) != 1) { |
| 2101 | throw new IllegalStateException("unable to find pending row for " |
| 2102 | + syncOperation); |
| 2103 | } |
| 2104 | |
| 2105 | if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */); |
| 2106 | } |
| 2107 | } |
| 2108 | |
| 2109 | public void dump(StringBuilder sb) { |
| 2110 | sb.append("SyncQueue: ").append(mOpsByWhen.size()).append(" operation(s)\n"); |
| 2111 | for (SyncOperation operation : mOpsByWhen) { |
| 2112 | sb.append(operation).append("\n"); |
| 2113 | } |
| 2114 | } |
| 2115 | |
| 2116 | private void debugCheckDataStructures(boolean checkDatabase) { |
| 2117 | if (mOpsByKey.size() != mOpsByWhen.size()) { |
| 2118 | throw new IllegalStateException("size mismatch: " |
| 2119 | + mOpsByKey .size() + " != " + mOpsByWhen.size()); |
| 2120 | } |
| 2121 | for (SyncOperation operation : mOpsByWhen) { |
| 2122 | if (!mOpsByKey.containsKey(operation.key)) { |
| 2123 | throw new IllegalStateException( |
| 2124 | "operation " + operation + " is in mOpsByWhen but not mOpsByKey"); |
| 2125 | } |
| 2126 | } |
| 2127 | for (Map.Entry<String, SyncOperation> entry : mOpsByKey.entrySet()) { |
| 2128 | final SyncOperation operation = entry.getValue(); |
| 2129 | final String key = entry.getKey(); |
| 2130 | if (!key.equals(operation.key)) { |
| 2131 | throw new IllegalStateException( |
| 2132 | "operation " + operation + " in mOpsByKey doesn't match key " + key); |
| 2133 | } |
| 2134 | if (!mOpsByWhen.contains(operation)) { |
| 2135 | throw new IllegalStateException( |
| 2136 | "operation " + operation + " is in mOpsByKey but not mOpsByWhen"); |
| 2137 | } |
| 2138 | } |
| 2139 | |
| 2140 | if (checkDatabase) { |
| 2141 | // check that the DB contains the same rows as the in-memory data structures |
| 2142 | Cursor cursor = mSyncStorageEngine.getPendingSyncsCursor(COLUMNS); |
| 2143 | try { |
| 2144 | if (mOpsByKey.size() != cursor.getCount()) { |
| 2145 | StringBuilder sb = new StringBuilder(); |
| 2146 | DatabaseUtils.dumpCursor(cursor, sb); |
| 2147 | sb.append("\n"); |
| 2148 | dump(sb); |
| 2149 | throw new IllegalStateException("DB size mismatch: " |
| 2150 | + mOpsByKey .size() + " != " + cursor.getCount() + "\n" |
| 2151 | + sb.toString()); |
| 2152 | } |
| 2153 | } finally { |
| 2154 | cursor.close(); |
| 2155 | } |
| 2156 | } |
| 2157 | } |
| 2158 | |
| 2159 | private SyncOperation cursorToOperation(Cursor cursor) { |
| 2160 | byte[] extrasData = cursor.getBlob(COLUMN_EXTRAS); |
| 2161 | Bundle extras; |
| 2162 | Parcel parcel = Parcel.obtain(); |
| 2163 | try { |
| 2164 | parcel.unmarshall(extrasData, 0, extrasData.length); |
| 2165 | parcel.setDataPosition(0); |
| 2166 | extras = parcel.readBundle(); |
| 2167 | } catch (RuntimeException e) { |
| 2168 | // A RuntimeException is thrown if we were unable to parse the parcel. |
| 2169 | // Create an empty parcel in this case. |
| 2170 | extras = new Bundle(); |
| 2171 | } finally { |
| 2172 | parcel.recycle(); |
| 2173 | } |
| 2174 | |
| 2175 | SyncOperation syncOperation = new SyncOperation( |
Fred Quintana | d9d2f11 | 2009-04-23 13:36:27 -0700 | [diff] [blame] | 2176 | new Account(cursor.getString(COLUMN_ACCOUNT), |
| 2177 | cursor.getString(COLUMN_ACCOUNT_TYPE)), |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 2178 | cursor.getInt(COLUMN_SOURCE), |
| 2179 | cursor.getString(COLUMN_AUTHORITY), |
| 2180 | extras, |
| 2181 | 0 /* delay */); |
| 2182 | syncOperation.rowId = cursor.getLong(COLUMN_ID); |
| 2183 | return syncOperation; |
| 2184 | } |
| 2185 | } |
| 2186 | } |