package android.content; import com.google.android.collect.Maps; import android.util.Pair; import android.util.Log; import android.accounts.Account; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import java.util.Iterator; /** * * @hide */ public class SyncQueue { private static final String TAG = "SyncManager"; private SyncStorageEngine mSyncStorageEngine; // A Map of SyncOperations operationKey -> SyncOperation that is designed for // quick lookup of an enqueued SyncOperation. private final HashMap mOperationsMap = Maps.newHashMap(); public SyncQueue(SyncStorageEngine syncStorageEngine) { mSyncStorageEngine = syncStorageEngine; ArrayList ops = mSyncStorageEngine.getPendingOperations(); final int N = ops.size(); for (int i=0; i nextOperation() { SyncOperation best = null; long bestRunTime = 0; for (SyncOperation op : mOperationsMap.values()) { long opRunTime = op.earliestRunTime; if (!op.extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF, false)) { Pair backoff = mSyncStorageEngine.getBackoff(op.account, op.authority); long delayUntil = mSyncStorageEngine.getDelayUntilTime(op.account, op.authority); opRunTime = Math.max( Math.max(opRunTime, delayUntil), backoff != null ? backoff.first : 0); } // if the expedited state of both ops are the same then compare their runtime. // Otherwise the candidate is only better than the current best if the candidate // is expedited. if (best == null || (best.expedited == op.expedited ? opRunTime < bestRunTime : op.expedited)) { best = op; bestRunTime = opRunTime; } } if (best == null) { return null; } return Pair.create(best, bestRunTime); } /** * Find and return the SyncOperation that should be run next and is ready to run. * @param now the current {@link android.os.SystemClock#elapsedRealtime()}, used to * decide if the sync operation is ready to run * @return the SyncOperation that should be run next and is ready to run. */ public Pair nextReadyToRun(long now) { Pair nextOpAndRunTime = nextOperation(); if (nextOpAndRunTime == null || nextOpAndRunTime.second > now) { return null; } return nextOpAndRunTime; } public void remove(Account account, String authority) { Iterator> entries = mOperationsMap.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = entries.next(); SyncOperation syncOperation = entry.getValue(); if (account != null && !syncOperation.account.equals(account)) { continue; } if (authority != null && !syncOperation.authority.equals(authority)) { continue; } entries.remove(); if (!mSyncStorageEngine.deleteFromPending(syncOperation.pendingOperation)) { final String errorMessage = "unable to find pending row for " + syncOperation; Log.e(TAG, errorMessage, new IllegalStateException(errorMessage)); } } } public void dump(StringBuilder sb) { sb.append("SyncQueue: ").append(mOperationsMap.size()).append(" operation(s)\n"); for (SyncOperation operation : mOperationsMap.values()) { sb.append(operation).append("\n"); } } }