Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Sipping on Battery Juice

Sipping on Battery Juice

Learn about battery consumption on Android and how to avoid it when building your apps.

[With Gifs] https://docs.google.com/presentation/d/1cvUzjGl9ljgRFrYk8j2Supc6Cxj1jHfBQF-WlJyNXIc/edit?usp=sharing

Nishant Srivastava

May 18, 2016
Tweet

More Decks by Nishant Srivastava

Other Decks in Technology

Transcript

  1. Sipping on Battery Juice! ..and how to save the battery

    from those “lil monster” apps.. - By Nishant Srivastava
  2. Nishant Srivastava Organizer, GDG New Delhi Software Engineer - Omni,

    Inc. Twitter - @nisrulz Github - nisrulz More Info About Me
  3. - Battery is #1 pain point of consumers. - With

    advancement in technology and increase in complexity of apps being built , the consumption of power also increase and battery drain would be more prominent. - Poorly built apps are resource hungry and result in dead battery, void of any juice left even before the day ends. - Everyone in the chain gets affected - Ad Networks - Publishers - Android devs - Users - Smartphone manufacturers - Battery is limited but it is also the main resource for a device to function. Once gone , its gone. - Battery is part of user experience, which means if your app is consuming a lot of power then more often than not , you will result in bad user experience and bad reviews in playstore.
  4. What costs more - Bulk Data transfers - Moving between

    cells/networks - Radio ramps up to associate with the new cell tower/network - Broadcast intents fired system wide - Wakeup of one app can start a cascade - Wakeup device when the app is in the background, basically stopping the device to be going into sleep when it should be . - Computational tasks like video/image processing
  5. ..Solution… - Buy external batteries - Buy a battery case

    (..and carry it around like a brick) - Use solar charging units
  6. To better understand the solution ..we need to know where

    exactly all of this power is being consumed ..
  7. As per research by various universities.. Most of the free

    apps consume around 30-40% of power on “game play” and the rest 70-60% is consumed by user tracking/analytics, ad downloads and uploading user information.
  8. Android Devices Complex Systems running on battery - Display, Input

    devices, sensors ,camera, CPU, GPU RAM, Storage, A/V Decoders, Speakers - Moore’s Law is not applicable to battery capacity ...yet.. - Demand for more performance or less power consumption is driven by use cases Network Calls - Analytics, fetching big chunks of data frequently , data sync, ad networks Location and Sensors - Always on, highest accuracy , maximum rate Inefficient code - Bad data structures, useless complexity in code paths.
  9. What does android do to help us - Project Volta

    - Doze Mode - Lifecycle method provision - Project Svelte But applications can easily ruin the battery of a device if not coded well. Which basically means that you are yourself responsible for all that battery drain, the os can only provide you only some sort of guard for free.
  10. Network Activity - The amount of power consumed by EDGE

    is pretty low for a byte of data transferred, but is slow. - Wifi is a huge power consumer but it can get the work done fast. - 3G consumes more power than WIFI but is typically slower than WIFI - 4G consumes even more power than 3G but in certain circumstances it can be faster than Wifi. In general this how the power consumers are ranked 4G>3g>Wifi> EDGE
  11. How does network drain my battery ? Things a network

    needs to do 1. Establishing connection or association 2. Maintaining association 3. Transmission (2 or more sub states) 4. Tail state (pseudo state) Power consumption based of the type of work Establish Maintain Transmit Tail Wifi High Low Low Low 2G Low Low Low Low 3G Low Low High High
  12. Unbundled vs Bundled transfers Suppose there are 3 data transfer

    each for 3s every 20s. Unbundled Transfer of 1 data = 3s+5s+12s =20s Now if there are 3 such transfers total time the radio is active = 20sx3=60s Bundled Transfer of all 3 data = 9s+5s+12s = 26s And thats everything ! Pretty neat eh ?
  13. Network Prefetch Data - To avoid switching states frequently, try

    and read as much data as possible - Trade off between too much prefetch and battery drain - Google recommends prefetching data so that you will only need to download more data after 2-5 minutes only and of the size of 1-5 mb. - Reduce in-app latency Batch data - Do data send receive in batches rather than on demand i.e batch analytics data rather than sending them as they are collected. - Create a pending queue and dispatch data when scheduled window arrives. - Detect Network connection type - Avoid trying to connect when there is no active network Avoid polling and use GCM - Avoid multiple connections - Reduce the number of device state changes Use inexact timer - Use setInexactRepeating - Do not use _WAKEUP version of alarms - Implement exponential backoff mechanism for polling
  14. Efficient Parsers - Use an efficient data format and parser

    - Use "stream" parsers instead of tree parsers - Consider binary formats that can easily mix binary and text data into a single request - Fewer round-trips to server for faster UX
  15. Services - Services should be short lived, remember they are

    not daemons - stopSelf() when finished - Trigger wakeup through AlarmManager and Broadcast Receivers.
  16. Battery State - Monitor charge level and state - Monitor

    docking state and type - Maximise updates when charging and reduce updates when discharging - When the battery is low, respect the user and stop all updates until battery is above low level.
  17. Wakelock - A wakelock is a mechanism to state that

    your app needs the device to stay on i.e cpu functional at full power, screen active , cellular activity active and any mechanism to save battery is ignored. - To keep the screen on - Certain apps need to keep the screen turned on, such as games or movie apps, use the FLAG_KEEP_SCREEN_ON in your activity (and only in an activity, never in a service or other app component) or use `androidkeepScreenOn` in your manifest. The advantage of this approach is that unlike wake locks (discussed in Keep the CPU On), it doesn't require special permission, and the platform correctly manages the user moving between applications, without your app needing to worry about releasing unused resources public class MainActivity extends Activity { @Override protected void onCreate (Bundle savedInstanceState ) { super.onCreate (savedInstanceState ); setContentView (R.layout.activity_main ); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } <RelativeLayout xmlns:android= "http://schemas.android. com/apk/res/android " android:layout_width= "match_parent " android:layout_height= "match_parent " android:keepScreenOn="true"> ... </RelativeLayout >
  18. ..get down to api.. - Use AlarmManager.set()/setInexactRepeating() + a pool

    of network requests. - Use SyncAdapter - Use JobScheduler API/ GCMNetworkManager API - Use GCM messages to trigger a sync only when needed. - Use traceview/method profiling in DDMS to check for race conditions. - Use LocationManager.NETWORK_PROVIDER wherever possible. - Use SENSOR_DELAY_NORMAL for sensors as the frequency of updates. - Try to send data over Wifi if possible. - Use GZIP for text data always.
  19. Contd.. - Use caches wherever possible - avoid redundant downloads

    - Vary the download pattern - Modify pattern based on connection quality - Change the aggression of pre-fetch i.e download more data on a faster network - Monitor the connectivity state - Manipulate Broadcast receivers on demand ComponentName receiver = new ComponentName (context, myReceiver .class); PackageManager pm = context.getPackageManager (); pm.setComponentEnabledSetting (receiver, PackageManager .COMPONENT_ENABLED_STATE_ENABLED , PackageManager .DONT_KILL_APP )
  20. Color & Brightness - Choose the right colors. - Color

    matters esp. on OLED Screens - Darker the color , lesser the impact. - Brightness levels matter too. - Programmatically reduce the brightness if it suits your app/activity Interesting stackoverflow question
  21. CPU - Spread Out your computationally intensive task - Avoid

    floating point math wherever possible. - Typically GPU consumes more power than a cpu. - Use GPU to do data parallel task like video/image processing - Use algorithms that consume less CPU cycles. The goal here is to keep the frequency as low as possible.
  22. GPS - Avoid fine grained location lookups and use getLastLocation()

    - GPS is one of the main power hungry unit in a device. - Use coarse location as much as possible.
  23. Network Connection Class - Facebook https://github.com/facebook/network- connection-class Listen to current

    network traffic in the app and categorize the quality of the network.
  24. Battery Historian - Google https://github.com/google/battery-historian Battery Historian is a tool

    to inspect battery related information and events on an Android device running Android 5.0 Lollipop (API level 21) and later, while the device was on battery. It allows application developers to visualize system and application level events on a timeline with panning and zooming functionality, easily see various aggregated statistics since the device was last fully charged, and select an application and inspect the metrics that impact battery specific to the chosen application. It also allows an A/B comparison of two bugreports, highlighting differences in key battery related metrics.