1page.title=Minimizing the Effect of Regular Updates
2parent.title=Transferring Data Without Draining the Battery
3parent.link=index.html
4
5trainingnavtop=true
6previous.title=Optimizing Downloads for Efficient Network Access
7previous.link=efficient-network-access.html
8next.title=Redundant Downloads are Redundant
9next.link=redundant_redundant.html
10
11@jd:body
12
13<div id="tb-wrapper">
14<div id="tb">
15
16<h2>This lesson teaches you to</h2>
17<ol>
18  <li><a href="#GCM">Use Google Cloud Messaging as an alternative to polling</a></li>
19  <li><a href="#OptimizedPolling">Optimize polling with inexact repeating alarms and exponential back-offs</a></li>
20</ol>
21
22<h2>You should also read</h2>
23<ul>
24  <li><a href="{@docRoot}training/monitoring-device-state/index.html">Optimizing Battery Life</a></li>
25  <li><a href="{@docRoot}google/gcm/index.html">Google Cloud Messaging for Android</a></li>
26</ul>
27
28</div>
29</div>
30
31<p>The optimal frequency of regular updates will vary based on device state, network connectivity, user behavior, and explicit user preferences.</p>
32
33<p><a href="{@docRoot}training/monitoring-device-state/index.html">Optimizing Battery Life</a> discusses how to build battery-efficient apps that modify their refresh frequency based on the state of the host device. That includes disabling background service updates when you lose connectivity and reducing the rate of updates when the battery level is low.</p>
34
35<p>This lesson will examine how your refresh frequency can be varied to best mitigate the effect of background updates on the underlying wireless radio state machine.</p>
36
37<h2 id="GCM">Use Google Cloud Messaging as an Alternative to Polling</h2>
38
39<p>Every time your app polls your server to check if an update is required, you activate the wireless radio, drawing power unnecessarily, for up to 20 seconds on a typical 3G connection.</p>
40
41<p><a href="{@docRoot}google/gcm/index.html">Google Cloud Messaging for Android (GCM)</a> is a lightweight mechanism used to transmit data from a server to a particular app instance. Using GCM, your server can notify your app running on a particular device that there is new data available for it.</p>
42
43<p>Compared to polling, where your app must regularly ping the server to query for new data, this event-driven model allows your app to create a new connection only when it knows there is data to download.</p>
44
45<p>The result is a reduction in unnecessary connections, and a reduced latency for updated data within your application.</p>
46
47<p>GCM is implemented using a persistent TCP/IP connection. While it's possible to implement your own push service, it's best practice to use GCM. This minimizes the number of persistent connections and allows the platform to optimize bandwidth and minimize the associated impact on battery life.</p>
48
49<h2 id="OptimizedPolling">Optimize Polling with Inexact Repeating Alarms and Exponential Backoffs</h2>
50
51<p>Where polling is required, it's good practice to set the default data refresh frequency of your app as low as possible without detracting from the user experience.</p>
52
53<p>A simple approach is to offer preferences to allow users to explicitly set their required update rate, allowing them to define their own balance between data freshness and battery life.</p>
54
55<p>When scheduling updates, use inexact repeating alarms that allow the system to "phase shift" the exact moment each alarm triggers.</p>
56
57<pre>int alarmType = AlarmManager.ELAPSED_REALTIME;
58long interval = AlarmManager.INTERVAL_HOUR;
59long start = System.currentTimeMillis() + interval;
60
61alarmManager.setInexactRepeating(alarmType, start, interval, pi);</pre>
62
63<p>If several alarms are scheduled to trigger at similar times, this phase-shifting will cause them to be triggered simultaneously, allowing each update to piggyback on top of a single active radio state change.</p>
64
65<p>Wherever possible, set your alarm type to {@code ELAPSED_REALTIME} or {@code RTC} rather than to their {@code _WAKEUP} equivalents. This further reduces battery impact by waiting until the phone is no longer in standby mode before the alarm triggers.</p>
66
67<p>You can further reduce the impact of these scheduled alarms by opportunistically reducing their frequency based on how recently your app was used.</p>
68
69<p>One approach is to implement an exponential back-off pattern to reduce the frequency of your updates (and / or the degree of prefetching you perform) if the app hasn't been used since the previous update. It's often useful to assert a minimum update frequency and to reset the frequency whenever the app is used, for example:</p>
70
71<pre>SharedPreferences sp =
72  context.getSharedPreferences(PREFS, Context.MODE_WORLD_READABLE);
73
74boolean appUsed = sp.getBoolean(PREFS_APPUSED, false);
75long updateInterval = sp.getLong(PREFS_INTERVAL, DEFAULT_REFRESH_INTERVAL);
76
77if (!appUsed)
78  if ((updateInterval *= 2) > MAX_REFRESH_INTERVAL)
79    updateInterval = MAX_REFRESH_INTERVAL;
80
81Editor spEdit = sp.edit();
82spEdit.putBoolean(PREFS_APPUSED, false);
83spEdit.putLong(PREFS_INTERVAL, updateInterval);
84spEdit.apply();
85
86rescheduleUpdates(updateInterval);
87executeUpdateOrPrefetch();</pre>
88
89<p>You can use a similar exponential back-off pattern to reduce the effect of failed connections and download errors.</p>
90
91<p>The cost of initiating a network connection is the same whether you are able to contact your server and download data or not. For time-sensitive transfers where successful completion is important, an exponential back-off algorithm can be used to reduce the frequency of retries in order to minimize the associated battery impact, for example:</p>
92
93<pre>private void retryIn(long interval) {
94  boolean success = attemptTransfer();
95
96  if (!success) {
97    retryIn(interval*2 < MAX_RETRY_INTERVAL ?
98            interval*2 : MAX_RETRY_INTERVAL);
99  }
100}</pre>
101
102<p>Alternatively, for transfers that are failure tolerant (such as regular updates), you can simply ignore failed connection and transfer attempts.</p>
103