diff --git a/docs/html/training/app/battery/index.jd b/docs/html/training/app/battery/index.jd index c8445d732e818..20341c55502cb 100644 --- a/docs/html/training/app/battery/index.jd +++ b/docs/html/training/app/battery/index.jd @@ -1,4 +1,48 @@ -page.title=Optimizing Battery Life +page.title=Battery Performance page.tags=battery +page.metaDescription=Learn how to optimize your app to reduce battery drain and use power-hungry resources efficiently. +page.article=true @jd:body + + + + +
+ Users want their devices to run as long as possible on a single charge of battery. As an app + developer, you should strive to make your app draw the minimum amount of power from the battery + without sacrificing responsiveness, speed or latency for the user. You can take steps to optimize + your app for maximum battery life by following the guidelines in this course. In many cases, + you can minimize battery consumption and still get the same amount of work done by being + more efficient. +
+ ++ When users notice their battery does not get them through the day, they commonly check their + device's Settings to find the offending app, where they can easily uninstall it. You should + analyze your app to see if it is a leading source of battery drain, and take steps to prevent + excessive battery consumption. +
+ ++ These lessons show you how to analyze your app for common sources of battery drain and fix them + in your app. +
+ ++ Some techniques for reducing the amount of network use can be applied to multiple network + use scenarios. After you complete your analysis and optimization of the primary network + access use case for your app, you should also look at these general-purpose techniques + and see if you can apply them to your app. +
+ ++ This lesson briefly covers techniques that you can use to lower network use and reduce the + impact your app has on battery life. +
+ ++ If you can reduce the amount of data sent or received over a network connection, this also + reduces the duration of the connection, which conserves battery. You can: +
+ ++ Your app can avoid downloading duplicate data by caching. Always cache static resources, + including on-demand downloads such as full size images, and cache them for as long as reasonably + possible. +
+ ++ For example, you should consider this approach for a networked app that displays data from + user-initiated network requests as the primary content on the screen. When the user opens this + screen the first time, the app should display a splash screen. Subsequent loads should initially + load with the data that was cached from the last network request. The screen reloads with + new data once the network request is complete. +
+ ++ To learn about caching, watch the video. To implement caching in your app, see Cache Files + Locally. +
+ + ++ Optimize pre-fetch cache size based on local file system size and current network connectivity. + You can use the connectivity manager to determine what type of networks (Wi-FI, LTE, HSPAP, EDGE, + GPRS) are active and modify your pre-fetching routines to minimize battery load. +
+ ++ For more information, see + Use + Modifying your Download Patterns Based on the Connectivity Type. +
\ No newline at end of file diff --git a/docs/html/training/app/battery/network/action-app-traffic.jd b/docs/html/training/app/battery/network/action-app-traffic.jd new file mode 100644 index 0000000000000..09746e9b0f5d5 --- /dev/null +++ b/docs/html/training/app/battery/network/action-app-traffic.jd @@ -0,0 +1,135 @@ +page.title=Optimizing App-Initiated Network Use +trainingnavtop=true + +@jd:body + ++ Network traffic initiated by your app can usually be significantly optimized, since you can plan + for what network resources it needs and set a schedule for accessing them. By applying careful + scheduling, you can create significant periods of rest for the device radio and, thereby, save + power. There are several Android APIs that can help with network access scheduling, and some of + these functions can coordinate network access for other apps, further optimizing battery + performance. +
+ ++ This lesson teaches you how to reduce battery consumption by applying techniques for + optimizing app-initiated network traffic. +
+ + ++ On a mobile device, the process of turning on the radio, making a connection, and keeping the + radio awake uses a large amount of power. For this reason, processing individual requests at + random times can consume significant power and reduce battery life. A more efficient approach is + to queue a set of network requests and process them together. This allows the system to pay the + power cost of turning on the radio just once, and still get all the data requested by an app. +
+ + + + ++ Using a network access scheduler API for queuing and processing your app data requests can + significantly increase the power efficiency of your app. Schedulers conserve battery power by + grouping requests together for the system to process. They can further improve efficiency by + delaying some requests until other requests wake up the mobile radio, or waiting until the + device is charging. Schedulers defer and batch network requests system-wide, across all apps on + the device, which gives them an optimizing advantage over what any individual app can do. +
+ + ++ Android provides three different APIs for your app to batch and schedule network requests. For + most operations, these techniques are functionally equivalent. These APIs are listed in the + following table with the most highly recommended first. +
+ +| Scheduler | +Requirements | +Implementation Ease | +
|---|---|---|
| + GCM Network Manager | +GCM Network Manager requires that your app use the Google Play services client library, + version 6.1.11 or higher. Use the latest available version. | +Straightforward | +
| Job Scheduler | +Job Scheduler does not require Google Play services, but is available only when targeting + Android 5.0 (API level 21) or higher. | +Straightforward | +
| Sync Adapter | +Sync Adapter does not require the Google Play services client library and has been + available since Android 2.0 (API level 5). | +Complex | +
+ Note: For scheduled data synchronization, you should always prefer GCM + Network Manager or Job Scheduler over Sync Adapter if your requirements allow it. +
+ + ++ One of the most serious and unexpected causes of battery drain is when a user travels beyond the + reach of any cell tower or access point. In this situation, the user is typically not using their + device, but they notice the device getting warm, and then see that the battery is low or has run + out. +
+ ++ In this scenario, the problem is that an app is running a background process that keeps + waking up the mobile radio at regular intervals to search for a cellular signal, but finds none. + Searching for a cell signal is one of the most power-draining operations there is. +
+ ++ The way to avoid causing this kind of problem for a user with your app is to use a + battery-efficient method for checking connectivity. For app-initiated network requests, use a + scheduler, which automatically uses Connectivity + Manager to check for connectivity before calling into your app. As a result, if there's no + network, the Connectivity Manager conserves battery because it performs the connectivity check + itself, without loading the app to run the check. Battery is further conserved because schedulers + use exponential + backoff to check for connectivity less frequently as time progresses. +
diff --git a/docs/html/training/app/battery/network/action-server-traffic.jd b/docs/html/training/app/battery/network/action-server-traffic.jd new file mode 100644 index 0000000000000..e5ac971e7289c --- /dev/null +++ b/docs/html/training/app/battery/network/action-server-traffic.jd @@ -0,0 +1,81 @@ +page.title=Optimizing Server-Initiated Network Use +trainingnavtop=true + + +@jd:body + ++ Network traffic sent by server programs to your app can be challenging to optimize. A + solution to this problem is to periodically poll the server from your app to check for updates. + This approach can waste network connection and power by starting up a device radio, only to + receive an answer that no new data is available. A more efficient approach would be for the + server to notify your app when it has new data, but figuring out how to send a notification from + your server to potentially thousands of devices is no easy feat. +
+ ++ The Google Cloud Messaging (GCM) + service solves this communication problem by allowing your servers to send notifications to + instances of your app wherever they are installed, enabling greater network efficiency and + lowering power usage. +
+ ++ This lesson teaches you how to apply the GCM service to reduce network use for server-initiated + actions and reduce battery consumption. +
+ + ++ Google Cloud Messaging (GCM) is a lightweight mechanism used to transmit brief messages from an + app server to your app. Using GCM, your app server uses a message-passing + mechanism to notify your app that there is new data available. This approach eliminates network + traffic that your app would perform, by not contacting a backend server for new data when there + is none available. +
+ ++ An example use of GCM is an app that lists speaker sessions at a conference. When sessions are + updated on your server, the server sends a message to your app telling it updates are available. + Your app can then call the server to update the sessions on the device only when there is new + data, rather than periodically contacting the server to find out if there are updates. +
+ ++ GCM is more efficient than polling for changes on the server. The service eliminates + unnecessary connections where polling would return no updates, and it avoids running periodic + network requests that could cause a device radio to power up. Since GCM can be used by many apps, + using it in your app reduces the total number of network connections needed on a device and + allows the device radio to sleep more often. +
+ ++ For more information about GCM and how to implement it for your app, see + Google Cloud Messaging. +
+ ++ Note: When using GCM, your app can pass messages in normal or high priority. + Your server should typically use + normal priority to deliver messages. Using this priority level prevents devices from being + woken up if they are inactive and in a low-power Doze + state. Use high priority messages only if absolutely required. +
diff --git a/docs/html/training/app/battery/network/action-user-traffic.jd b/docs/html/training/app/battery/network/action-user-traffic.jd new file mode 100644 index 0000000000000..4d73ff3ebc175 --- /dev/null +++ b/docs/html/training/app/battery/network/action-user-traffic.jd @@ -0,0 +1,122 @@ +page.title=Optimizing User-Initiated Network Use +trainingnavtop=true + +@jd:body + ++ Quick handling of user requests helps ensure a good user experience, especially when it comes to + user actions that require network access. You should prioritize low latency over power + conservation to provide the fastest response when optimizing network use that is a direct result + of user actions. Attaining an optimal network traffic profile for your app, while making sure + that your users get fast responses, can be a bit challenging. +
+ ++ This lesson teaches you how to optimize network use for user-initiated + actions and reduce battery consumption. +
+ + ++ Pre-fetching data is an effective way to reduce the number of independent data transfer sessions + that your app runs. With pre-fetching, when the user performs an action in your app, the app + anticipates data that will most likely be needed for the next user actions and fetches that data + in bulk. Battery power consumption is reduced because the pre-fetched data does not require + separate requests that each incur the overhead of waking up the mobile radio. +
+ ++ Tip: To explore whether your app might benefit from pre-fetching, review your + app's network traffic and look for situations where a specific series of user actions almost + always results in multiple network requests over the course of the task. For instance, an app + that incrementally downloads article content as a user views it might be able to pre-fetch one or + more articles in categories the user is known to view. +
+ ++ Watch the video on effective pre-fetching below which describes what pre-fetching is, where to + use it, and how much data to pre-fetch. For more details, see Optimizing + Downloads for Efficient Network Access. +
+ + ++ Searching for a cell signal is one of the most power-draining operations on a mobile + device. Your app should always check for connectivity before sending a user-initiated network + request. If you use a scheduling service, the service does this automatically for you. Fo + + (Schedulers do this automatically for you.) +
+ ++ A best practice for user-initiated traffic is to first check for a connection using Connectivity Manager, and if there + is no connection, schedule the network request for when the + connection is made. Schedulers will use techniques such as exponential backoff to save battery, + where each time the attempt to connect fails, the scheduler doubles the delay before the next + retry. +
+ ++ Note: To check for connectivity for app-initiated traffic, see Optimizing App-Initiated Network Use. +
+ + ++ In general, it's 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. For more information on reducing the number of connections used by your app, + see + Optimizing Downloads for Efficient Network Access. +
diff --git a/docs/html/training/app/battery/network/analyze-data.jd b/docs/html/training/app/battery/network/analyze-data.jd new file mode 100644 index 0000000000000..03efa05f6c486 --- /dev/null +++ b/docs/html/training/app/battery/network/analyze-data.jd @@ -0,0 +1,225 @@ +page.title=Analyzing Network Traffic Data +trainingnavtop=true + +@jd:body + ++ Gathering data about the network access behavior of your app is the first step toward optimizing + your app's use of network hardware, and making your app more power efficient. After you have + tagged your app code with traffic identifiers, run tests, and collected data, it is time to + analyze that data. +
+ ++ This lesson teaches you how to look at the network traffic data you have collected from your app + and directs you to actions for improving your app's networking performance and reducing power + consumption. +
+ + ++ Efficient use of network resources by an app is characterized by significant periods where + the network hardware is not in use. + + On mobile devices, there is a significant cost associated with starting up the radio + to send or receive data, and with keeping the mobile radio active for long periods. If your app + is accessing the network efficiently, you should see that its communications over the network are + tightly grouped together, well spaced with periods where the app is making no connection requests. +
+ ++ Figure 1 shows suboptimal network traffic from app, as measured by the Network Traffic tool. The + app is making frequent network requests. This traffic has few periods of + rest where the radio could switch to a standby, low-power mode. The network access behavior of + this app is likely to keep the radio on for extended periods of time, which is + battery-inefficient. +
+ +
++ Figure 1. Battery-inefficient network activity measured from an app. +
+ ++ Figure 2 shows an optimal network traffic pattern. The app sends network requests in bursts, + separated by long periods of no traffic where the radio can switch to standby. This chart shows + the same amount of work being done as Figure 1, but the requests have been shifted and grouped to + allow the radio to be in standby most of the time. +
+ +
++ Figure 2. Battery-efficient network activity measured from an app. +
+ ++ If the network traffic for your app looks similar to the graph in Figure 2, you are in good + shape! Congratulations! You may want to pursue further networking efficiency by checking out the + techniques described in Optimizing General Network + Use +
+ ++ If the network traffic for your app looks more like the graph in Figure 1, it's time to take a + harder look at how your app accesses the network. You should start by analyzing what types of + network traffic your app is generating. +
+ + ++ When you look at the network traffic generated by your app, you need to understand the source of + the traffic, so you can optimize it appropriately. Frequent network activity generated by your + app may be entirely appropriate if it is responding to user actions, but completely inappropriate + if you app is not in the foreground or if the device in a pocket or purse. This section discusses + how to analyze the types of network traffic being generated by your app and directs you to + actions you can take to improve performance. +
+ ++ In the previous lesson, you tagged your app code for different traffic types and used the Network + Traffic tool to collect data on your app and produce a graph of activity, as shown in Figure 3. +
+
++ Figure 3. Network traffic tagged for the three categories: user, app, and + server. +
+ ++ The Network Traffic tool colors traffic based on the tags you created in the previous lesson. The + colors are based on the traffic type constants you defined in + your app code. Refer back to your app code to confirm which constants represent user, app, or + server-initiated traffic. +
+ ++ The following sections discuss how to look at network traffic types and provides recommendations + on how to optimize traffic. +
+ + ++ Network activity initiated by the user may be efficiently grouped together while a user is + performing a specific activity with your app, or spread out unevenly as users request additional + information your app does not have. Your goal in analyzing user-initiated network traffic is to + look for patterns of frequent network use over time and attempt to create, or increase the size + of, periods where the network is not accessed. +
+ ++ The unpredictability of user requests makes it challenging to optimize this type of network use + in your app. In addition, users expect fast responses when they are actively using an app, so + delaying requests for efficiency can lead to poor user experiences. In general, you should + prioritize a quick response to the user over efficient use of the network while a user is + directly interacting with your app. +
+ ++ Here are some approaches for optimizing user-initiated network traffic: +
+ ++ Caution: Beware of network activity grouping bias in your user activity test + data! If you ran a set of user scenarios with your network testing plan, the graph of + user-initiated network access may be unrealistically grouped together, potentially causing you to + optimize for user behavior that does not actually occur. Make sure your user network test + scenarios reflect realistic use of your app. +
+ + ++ Network activity initiated by your app code is typically an area where you can have a significant + impact on the efficient use of network bandwidth. In analyzing the network activity of your app, + look for periods of inactivity and determine if they can be increased. If you see patterns of + consistent network access from your app, look for ways to space out these accesses to allow the + device radio to switch into low power mode. +
+ ++ Here are some approaches for optimizing app-initiated network traffic: +
+ ++ Network activity initiated by servers communicating with your app is also typically an area where + you can have a significant impact on the efficient use of network bandwidth. In analyzing the + network activity from server connections, look for periods of inactivity and determine if they + can be increased. If you see patterns of consistent network activity from servers, look for ways + to space out this activity to allow the device radio to switch into low power mode. +
+ ++ Here is an approach for optimizing app-initiated network traffic: +
+ ++ The network traffic generated by an app can have a significant impact on the battery life of the + device where it is running. In order to optimize that traffic, you need to both measure it and + identify its source. Network requests can come directly from a user action, requests from your own + app code, or from a server communicating with your app. +
+ ++ The Network Traffic tool (part of the + DDMS tools) enables you to view how and when your app transfers data over a network. +
+ ++ This lesson shows you how to measure and categorize network requests by tagging your source code, + then shows you how to deploy, test and visualize your apps's network traffic. +
+ + ++ Apps use the networking hardware on a device for various reasons. In order to properly optimize + your app's use of networking resources, you must understand how frequently your app is using the + network and for what reasons. For performance analysis purposes, you should break down use of + network hardware into these categories: +
+ ++ This procedure shows you how to tag your app's source code with constants to categorize traffic + as one of these three request types. The Network Traffic tool represents each type of traffic + with a different color, so you can visualize and optimize each traffic stream separately. + The technique described here reports network traffic based on the execution of threads in your + app which you identify as a user, app or server source. +
+ ++public static final int USER_INITIATED = 0x1000; +public static final int APP_INITIATED = 0x2000; +public static final int SERVER_INITIATED =0x3000; ++
extends GcmTaskService|extends JobService|extends
+ AbstractThreadedSyncAdapter|HttpUrlConnection|Volley|Glide|HttpClient
+ *.java.
+if (BuildConfig.NETWORK-TEST && Build.VERSION.SDK_INT >= 14) {
+ try {
+ TrafficStats.setThreadStatsTag(USER_INITIATED);
+ // make network request using HttpClient.execute()
+ } finally {
+ TrafficStats.clearThreadStatsTag();
+ }
+}
+
+
+
+ Note: Ensure the tagging does not get into your production code by making
+ inclusion of this conditional, based on the build type used to generate the APK.
+ In the example above, the BuildConfig.NETWORK-TEST field identifies this
+ APK as a test version.
+
+ Note: This technique for tagging network traffic from your app depends on + how the APIs you are using access and manage network sockets. Some networking libraries may + not allow the {@link android.net.TrafficStats} utilities to tag traffic from your app. +
+ ++ For more information about tagging and tracking network traffic with the Network Traffic tool, + see Detailed Network Usage + in DDMS. +
+ + +
+ When you run performance tests, your APK should be as close as possible to the production
+ build. In order to achieve this for your network testing, create a network-test
+ build type, rather than using debug build type.
+
build.gradle file as shown in the following code example:
+
+
+android {
+ ...
+ buildTypes {
+ debug {
+ // debuggable true is default for the debug buildType
+ }
+ network-test {
+ debuggable true
+ }
+ }
+ ...
+}
+
+ + To deploy the APK generated by the {@code network-test} build type configured in the previous + proceedure: +
+ +network-test for the app module.
+ network-test from the list.
+ + The Network Traffic tool in Android Studio helps you see how your app uses network resources + while it is running. When running the tool with your app to test performance, you should have a + testing plan that exercises the primary functionality of the app, simulating a user interacting + with your app. You should also include idle time in your test plan, simulating periods when + users are not directly interacting with your app. +
+ ++ To improve the repeatability of your testing, you should start with a known initial state for + your app by clearing app data. The following procedure shows you how to stop your app and clear + all app data including previously cached data and networking data. This step puts your + app back to a state where it must re-cache all previously cached data. Do not skip this step. +
+ ++ To start the Network Traffic tool and visualize the network requests: +
+ ++ Note: You may be prompted to Allow USB Debugging on your + device. Select OK to allow debugging to proceed. +
++adb shell pm clear package.name.of.app ++
+ Use of tagging for network traffic helps you visually distinguish each request category by + producing a different color for each network traffic in the Network Traffic tool, as shown in + Figure 1. +
+ +
++ Figure 1. Network traffic tagged for the three categories. +
diff --git a/docs/html/training/app/battery/network/index.jd b/docs/html/training/app/battery/network/index.jd new file mode 100644 index 0000000000000..e0220653a24e2 --- /dev/null +++ b/docs/html/training/app/battery/network/index.jd @@ -0,0 +1,87 @@ +page.title=Reducing Network Battery Drain +page.article=true + +page.tags=battery +page.metaDescription=Learn how to optimize your app to reduce battery drain and use network resources efficiently. + +@jd:body + + + + ++ Requests that your app makes to the network are a major cause of battery drain because they turn + on the power-hungry mobile or Wi-Fi radios. Beyond the energy needed to send and receive packets, + these radios expend extra power just turning on and keeping awake. Something as simple as a + network request every 15 seconds can keep the mobile radio on continuously and quickly use up + battery power. +
+ ++ This lesson shows you how to visualize network traffic and you how to tag and categorize your + app's source code to color-code your network requests according to how they are initiated, then + profile the network traffic. From there, each category identifies areas of your app that you can + make more battery-efficient. +
+ + +