1page.title=Optimizing Downloads for Efficient Network Access
2parent.title=Transferring Data Without Draining the Battery
3parent.link=index.html
4
5trainingnavtop=true
6next.title=Minimizing the Effect of Regular Updates
7next.link=regular_updates.html
8
9@jd:body
10
11<div id="tb-wrapper">
12<div id="tb">
13
14<h2>This lesson teaches you to</h2>
15<ol>
16  <li><a href="#RadioStateMachine">Understand the radio state machine</a></li>
17  <li><a href="#AppsStateMachine">Understand how apps can impact the radio state machine</a></li>
18  <li><a href="#PrefetchData">Efficiently prefetch data</a></li>
19  <li><a href="#BatchTransfers">Batch transfers and connections</a></li>
20  <li><a href="#ReduceConnections">Reduce the number of connections you use</a></li>
21  <li><a href="#DDMSNetworkTraffic">Use the DDMS Network Traffic Tool to identify areas of concern</a></li>
22</ol>
23
24<h2>You should also read</h2>
25<ul>
26  <li><a href="{@docRoot}training/monitoring-device-state/index.html">Optimizing Battery Life</a></li>
27</ul>
28
29</div>
30</div>
31
32<p>Using the wireless radio to transfer data is potentially one of your app's most significant sources of battery drain. To minimize the battery drain associated with network activity, it's critical that you understand how your connectivity model will affect the underlying radio hardware.</p>
33
34<p>This lesson introduces the wireless radio state machine and explains how your app's connectivity model interacts with it. It goes on to propose ways to minimize your data connections, use prefetching, and bundle your transfers in order to minimize the battery drain associated with your data transfers.</p>
35
36<h2 id="RadioStateMachine">The Radio State Machine</h2>
37
38<p>A fully active wireless radio consumes significant power, so it transitions between different energy states in order to conserve power when not in use, while attempting to minimize latency associated with "powering up" the radio when it's required.</p>
39
40<p>The state machine for a typical 3G network radio consists of three energy states:
41<ol><li><b>Full power</b>: Used when a connection is active, allowing the device to transfer data at its highest possible rate.</li>
42<li><b>Low power</b>: An intermediate state that uses around 50% of the battery power at the full state.</li>
43<li><b>Standby</b>: The minimal energy state during which no network connection is active or required.</li>
44</ol></p>
45
46<p>While the low and idle states drain significantly less battery, they also introduce significant latency to network requests. Returning to full power from the low state takes around 1.5 seconds, while moving from idle to full can take over 2 seconds.</p>
47
48<p>To minimize latency, the state machine uses a delay to postpone the transition to lower energy states. Figure 1 uses AT&T's timings for a typical 3G radio.</p>
49
50<img src="{@docRoot}images/efficient-downloads/mobile_radio_state_machine.png" />
51<p class="img-caption"><strong>Figure 1.</strong> Typical 3G wireless radio state machine.</p>
52
53<p>The radio state machine on each device, particularly the associated transition delay ("tail time") and startup latency, will vary based on the wireless radio technology employed (2G, 3G, LTE, etc.) and is defined and configured by the carrier network over which the device is operating.</p>
54
55<p>This lesson describes a representative state machine for a typical 3G wireless radio, based on <a href="http://www.research.att.com/articles/featured_stories/2011_03/201102_Energy_efficient?fbid=1zObBOMOZSB">data provided by AT&T</a>. However, the general principles and resulting best practices are applicable for all wireless radio implementations.</p>
56
57<p>This approach is particularly effective for typical web browsing as it prevents unwelcome latency while users browse the web. The relatively low tail-time also ensures that once a browsing session has finished, the radio can move to a lower energy state.</p>
58
59<p>Unfortunately, this approach can lead to inefficient apps on modern smartphone OSs like Android, where apps run both in the foreground (where latency is important) and in the background (where battery life should be prioritized).</p>
60
61<h2 id="AppsStateMachine">How Apps Impact the Radio State Machine</h2>
62
63<p>Every time you create a new network connection, the radio transitions to the full power state. In the case of the typical 3G radio state machine described above, it will remain at full power for the duration of your transfer&mdash;plus an additional 5 seconds of tail time&mdash;followed by 12 seconds at the low energy state.  So for a typical 3G device, every data transfer session will cause the radio to draw energy for almost 20 seconds.</p>
64
65<p>In practice, this means an app that transfers unbundled data for 1 second every 18 seconds will keep the wireless radio perpetually active, moving it back to high power just as it was about to become idle. As a result, every minute it will consume battery at the high power state for 18 seconds, and at the low power state for the remaining 42 seconds.</p>
66
67<p>By comparison, the same app that bundles transfers of 3 seconds of every minute will keep the radio in the high power state for only 8 seconds, and will keep it in the low power state for only an additional 12 seconds.</p>
68
69<p>The second example allows the radio to be idle for an additional 40 second every minute, resulting in a massive reduction in battery consumption.</p>
70
71<img src="{@docRoot}images/efficient-downloads/graphs.png" />
72<p class="img-caption"><strong>Figure 2.</strong> Relative wireless radio power use for bundled versus unbundled transfers.</p>
73
74<h2 id="PrefetchData">Prefetch Data</h2>
75
76<p>Prefetching data is an effective way to reduce the number of independent data transfer sessions. Prefetching allows you to download all the data you are likely to need for a given time period in a single burst, over a single connection, at full capacity.</p>
77
78<p>By front loading your transfers, you reduce the number of radio activations required to download the data. As a result you not only conserve battery life, but also improve the latency, lower the required bandwidth, and reduce download times.</p>
79
80<p>Prefetching also provides an improved user experience by minimizing in-app latency caused by waiting for downloads to complete before performing  an action or viewing data.</p>
81
82<p>However, used too aggressively, prefetching introduces the risk of increasing battery drain and bandwidth use&mdash;as well as download quota&mdash;by downloading data that isn't used. It's also important to ensure that prefetching doesn't delay application startup while the app waits for the prefetch to complete. In practical terms that might mean processing data progressively, or initiating consecutive transfers prioritized such that the data required for application startup is downloaded and processed first.</p>
83
84<p>How aggressively you prefetch depends on the size of the data being downloaded and the likelihood of it being used. As a rough guide, based on the state machine described above, for data that has a 50% chance of being used within the current user session, you can typically prefetch for around 6 seconds (approximately 1-2 Mb) before the potential cost of downloading unused data matches the potential savings of not downloading that data to begin with.</p>
85
86<p>Generally speaking, it's good practice to prefetch data such that you will only need to initiate another download every 2 to 5 minutes, and in the order of 1 to 5 megabytes.</p>
87
88<p>Following this principle, large downloads&mdash;such as video files&mdash;should be downloaded in chunks at regular intervals (every 2 to 5 minutes), effectively prefetching only the video data likely to be viewed in the next few minutes.</p>
89
90<p>Note that further downloads should be bundled, as described in the next section, <a href="#BatchTransfers">Batch Transfers and Connections</a>, and that these approximations will vary based on the connection type and speed, as discussed in <a href="connectivity_patterns.html">Modify your Download Patterns Based on the Connectivity Type</a>.</p>
91
92<p>Let's look at some practical examples:</p>
93
94<p><b>A music player</b></p>
95
96<p>You could choose to prefetch an entire album, however should the user stop listening after the first song, you've wasted a significant amount of bandwidth and battery life.</p>
97
98<p>A better approach would be to maintain a buffer of one song in addition to the one being played. For streaming music, rather than maintaining a continuous stream that keeps the radio active at all times, consider using HTTP live streaming to transmit the audio stream in bursts, simulating the prefetching approach described above.</p>
99
100<p><b>A news reader</b></p>
101
102<p>Many news apps attempt to reduce bandwidth by downloading headlines only after a category has been selected, full articles only when the user wants to read them, and thumbnails just as they scroll into view.</p>
103
104<p>Using this approach, the radio will be forced to remain active for the majority of users' news-reading session as they scroll headlines, change categories, and read articles. Not only that, but the constant switching between energy states will result in significant latency when switching categories or reading articles.</p>
105
106<p>A better approach would be to prefetch a reasonable  amount of data at startup, beginning with the first set of news headlines and thumbnails&mdash;ensuring a low latency startup time&mdash;and continuing with the remaining headlines and thumbnails, as well as the article text for each article available from at least the primary headline list.</p>
107
108<p>Another alternative is to prefetch every headline, thumbnail, article text, and possibly even full article pictures&mdash;typically in the background on a predetermined schedule. This approach risks spending significant bandwidth and battery life downloading content that's never used, so it should be implemented with caution.</p>
109
110<p>One solution is to schedule the full download to occur only when connected to Wi-Fi, and possibly only when the device is charging. This is investigated in more detail in <a href="connectivity_patterns.html">Modify your Download Patterns Based on the Connectivity Type</a>.</p>
111
112<h2 id="BatchTransfers">Batch Transfers and Connections</h2>
113
114Every time you initiate a connection&mdash;irrespective of the size of the associated data transfer&mdash;you potentially cause the radio to draw power for nearly 20 seconds when using a typical 3G wireless radio.</p>
115
116<p>An app that pings the server every 20 seconds, just to acknowledge that the app is running and visible to the user, will keep the radio powered on indefinitely, resulting in a significant battery cost for almost no actual data transfer.</p>
117
118<p>With that in mind it's important to bundle your data transfers and create a pending transfer queue. Done correctly, you can effectively phase-shift transfers that are due to occur within a similar time window, to make them all happen simultaneously&mdash;ensuring that the radio draws power for as short a duration as possible.</p>
119
120<p>The underlying philosophy of this approach is to transfer as much data as possible during each transfer session in an effort to limit the number of sessions you require.</p>
121
122<p>That means you should batch your transfers by queuing delay tolerant transfers, and preempting scheduled updates and prefetches, so that they are all executed when time-sensitive transfers are required. Similarly, your scheduled updates and regular prefetching should initiate the execution of your pending transfer queue.</p>
123
124<p>For a practical example, let's return to the earlier examples from <a href="#PrefetchData">Prefetch Data</a>.</p>
125
126<p>Take a news application that uses the prefetching routine described above. The news reader collects analytics information to understand the reading patterns of its users and to rank the most popular stories. To keep the news fresh, it checks for updates every hour. To conserve bandwidth, rather than download full photos for each article, it prefetches only thumbnails and downloads the full photos when they are selected.</p>
127
128<p>In this example, all the analytics information collected within the app should be bundled together and queued for download, rather than being transmitted as it's collected. The resulting bundle should be transferred when either a full-sized photo is being downloaded, or when an hourly update is being performed.</p>
129
130<p>Any time-sensitive or on-demand transfer&mdash;such as downloading a full-sized image&mdash;should preempt regularly scheduled updates. The planned update should be executed at the same time as the on-demand transfer, with the next update scheduled to occur after the set interval. This approach mitigates the cost of performing a regular update by piggy-backing on the necessary time-sensitive photo download.</p>
131
132<h2 id="ReduceConnections">Reduce Connections</h2>
133
134<p>It's generally more efficient to reuse existing network connections than to initiate new ones. Reusing connections also allows the network to more intelligently react to congestion and related network data issues.</p>
135
136<p>Rather than creating multiple simultaneous connections to download data, or chaining multiple consecutive GET requests, where possible you should bundle those requests into a single GET.</p>
137
138<p>For example, it would be more efficient to make a single request for every news article to be returned in a single request / response than to make multiple queries for several news categories.
139The wireless radio needs to become active in order to transmit the termination / termination acknowledgement packets associated with server and client  timeout, so it's also good practice to close your connections when they aren't in use, rather than waiting for these timeouts.</p>
140
141<p>That said, closing a connection too early can prevent it from being reused, which then requires additional overhead for establishing a new connection. A useful compromise is not to close the connection immediately, but to still close it before the inherent timeout expires.</p>
142
143<h2 id="DDMSNetworkTraffic">Use the DDMS Network Traffic Tool to Identify Areas of Concern</h2>
144
145<p>The Android <a href="{@docRoot}tools/debugging/ddms.html">DDMS (Dalvik Debug Monitor Server)</a> includes a Detailed Network Usage tab that makes it possible to track when your application is making network requests. Using this tool, you can monitor how and when your app transfers data and optimize the underlying code appropriately.</p>
146
147<p>Figure 3 shows a pattern of transferring small amounts of data roughly 15 seconds apart, suggesting that efficiency could be dramatically improved by prefetching each request or bundling the uploads.</p>
148
149<img src="{@docRoot}images/efficient-downloads/DDMS.png" />
150<p class="img-caption"><strong>Figure 3.</strong> Tracking network usage with DDMS.</p>
151
152<p>By monitoring the frequency of your data transfers, and the amount of data transferred during each connection, you can identify areas of your application that can be made more battery-efficient. Generally, you will be looking for short spikes that can be delayed, or that should cause a later transfer to be preempted.</p>
153
154<p>To better identify the cause of transfer spikes, the Traffic Stats API allows you to tag the data transfers occurring within a thread using the {@code TrafficStats.setThreadStatsTag()} method, followed by manually tagging (and untagging) individual sockets using {@code tagSocket()} and {@code untagSocket()}. For example:</p>
155
156<pre>TrafficStats.setThreadStatsTag(0xF00D);
157TrafficStats.tagSocket(outputSocket);
158// Transfer data using socket
159TrafficStats.untagSocket(outputSocket);</pre>
160
161<p>The Apache {@code HttpClient} and {@code URLConnection} libraries automatically tag sockets based on the current {@code getThreadStatsTag()} value. These libraries also tag and untag sockets when recycled through keep-alive pools.</p>
162
163<pre>TrafficStats.setThreadStatsTag(0xF00D);
164try {
165  // Make network request using HttpClient.execute()
166} finally {
167  TrafficStats.clearThreadStatsTag();
168}</pre>
169
170<p>Socket tagging is supported in Android 4.0, but real-time stats will only be displayed on devices running Android 4.0.3 or higher.</p>