michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.sync; michael@0: michael@0: import android.content.SharedPreferences; michael@0: import android.content.SharedPreferences.Editor; michael@0: michael@0: public class PrefsBackoffHandler implements BackoffHandler { michael@0: public static final String PREF_EARLIEST_NEXT = "earliestnext"; michael@0: michael@0: private final SharedPreferences prefs; michael@0: private final String prefEarliest; michael@0: michael@0: public PrefsBackoffHandler(final SharedPreferences prefs, final String prefSuffix) { michael@0: if (prefs == null) { michael@0: throw new IllegalArgumentException("prefs must not be null."); michael@0: } michael@0: this.prefs = prefs; michael@0: this.prefEarliest = PREF_EARLIEST_NEXT + "." + prefSuffix; michael@0: } michael@0: michael@0: @Override michael@0: public synchronized long getEarliestNextRequest() { michael@0: return prefs.getLong(prefEarliest, 0); michael@0: } michael@0: michael@0: @Override michael@0: public synchronized void setEarliestNextRequest(final long next) { michael@0: final Editor edit = prefs.edit(); michael@0: edit.putLong(prefEarliest, next); michael@0: edit.commit(); michael@0: } michael@0: michael@0: @Override michael@0: public synchronized void extendEarliestNextRequest(final long next) { michael@0: if (prefs.getLong(prefEarliest, 0) >= next) { michael@0: return; michael@0: } michael@0: final Editor edit = prefs.edit(); michael@0: edit.putLong(prefEarliest, next); michael@0: edit.commit(); michael@0: } michael@0: michael@0: /** michael@0: * Return the number of milliseconds until we're allowed to touch the server again, michael@0: * or 0 if now is fine. michael@0: */ michael@0: @Override michael@0: public long delayMilliseconds() { michael@0: long earliestNextRequest = getEarliestNextRequest(); michael@0: if (earliestNextRequest <= 0) { michael@0: return 0; michael@0: } michael@0: long now = System.currentTimeMillis(); michael@0: return Math.max(0, earliestNextRequest - now); michael@0: } michael@0: }