|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 package org.mozilla.gecko.sync; |
|
6 |
|
7 import android.content.SharedPreferences; |
|
8 import android.content.SharedPreferences.Editor; |
|
9 |
|
10 public class PrefsBackoffHandler implements BackoffHandler { |
|
11 public static final String PREF_EARLIEST_NEXT = "earliestnext"; |
|
12 |
|
13 private final SharedPreferences prefs; |
|
14 private final String prefEarliest; |
|
15 |
|
16 public PrefsBackoffHandler(final SharedPreferences prefs, final String prefSuffix) { |
|
17 if (prefs == null) { |
|
18 throw new IllegalArgumentException("prefs must not be null."); |
|
19 } |
|
20 this.prefs = prefs; |
|
21 this.prefEarliest = PREF_EARLIEST_NEXT + "." + prefSuffix; |
|
22 } |
|
23 |
|
24 @Override |
|
25 public synchronized long getEarliestNextRequest() { |
|
26 return prefs.getLong(prefEarliest, 0); |
|
27 } |
|
28 |
|
29 @Override |
|
30 public synchronized void setEarliestNextRequest(final long next) { |
|
31 final Editor edit = prefs.edit(); |
|
32 edit.putLong(prefEarliest, next); |
|
33 edit.commit(); |
|
34 } |
|
35 |
|
36 @Override |
|
37 public synchronized void extendEarliestNextRequest(final long next) { |
|
38 if (prefs.getLong(prefEarliest, 0) >= next) { |
|
39 return; |
|
40 } |
|
41 final Editor edit = prefs.edit(); |
|
42 edit.putLong(prefEarliest, next); |
|
43 edit.commit(); |
|
44 } |
|
45 |
|
46 /** |
|
47 * Return the number of milliseconds until we're allowed to touch the server again, |
|
48 * or 0 if now is fine. |
|
49 */ |
|
50 @Override |
|
51 public long delayMilliseconds() { |
|
52 long earliestNextRequest = getEarliestNextRequest(); |
|
53 if (earliestNextRequest <= 0) { |
|
54 return 0; |
|
55 } |
|
56 long now = System.currentTimeMillis(); |
|
57 return Math.max(0, earliestNextRequest - now); |
|
58 } |
|
59 } |