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. ..everyone in the room be like ... yeah, I know

    that ..right ?
  3. Nishant Srivastava Organizer, GDG New Delhi Software Engineer - Omni,

    Inc. Twitter - @nisrulz Github - nisrulz More Info About Me
  4. The Problem

  5. - 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.
  6. 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
  7. ..and this is how a user ends up at the

    end of the day...
  8. Solution ?

  9. ..Solution… - Buy external batteries - Buy a battery case

    (..and carry it around like a brick) - Use solar charging units
  10. The <Actual> Solution ..ok..no kidding ..

  11. To better understand the solution ..we need to know where

    exactly all of this power is being consumed ..
  12. What/Who is eating my battery ?

  13. Taken from Jeff Sharkey’s Presentation Google I/O 2009

  14. 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.
  15. All the people in the room be like .. Waaaaaaaaa

    a… ( eyebrow raised )
  16. To understand more lets dive deeper...

  17. 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.
  18. 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.
  19. 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
  20. 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
  21. More about states Time between state reduction = Tail state

  22. 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 ?
  23. Best practices

  24. 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
  25. Taken from Jeff Sharkey’s Presentation Google I/O 2009

  26. 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
  27. Services - Services should be short lived, remember they are

    not daemons - stopSelf() when finished - Trigger wakeup through AlarmManager and Broadcast Receivers.
  28. 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.
  29. 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 >
  30. ..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.
  31. 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 )
  32. If you all aren’t asleep yet .. .there is more

  33. 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
  34. 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.
  35. 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.
  36. Tools to help you in hunting issues with battery

  37. 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.
  38. 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.
  39. None
  40. Use the Network Monitor in Android Studio

  41. Questions ?

  42. Ands thats all for today folks !

  43. References https://developer.android.com/training/efficient-downloads/index.html https://developer.android.com/training/monitoring-device-state/index.html https://dl.google.com/io/2009/pres/W_0300_CodingforLife-BatteryLifeThatIs.pdf http://people.cs.umass.edu/~arun/papers/TailEnder.pdf http://www.ruf.rice.edu/~mobile/publications/dong10chameleon-demo.pdf http://www.slideshare.net/littleeye/power-optimization-for-android-developers http://stackoverflow.com/q/19141050/2745762 Presentation by

    Jeff Sharkey from Google I/O 2009
  44. GDG New Delhi Google Space : https://goo.gl/spaces/DCQj3gc94dsbH4By5 Slack : gdgnd.slack.com

    Mail : [email protected] Twitter : @gdg_nd , @gdgndbot Facebook : gdgnewdelhi