Android App: Battery Optimization Best Practices for Zero Compromise on Performance

5 minutes read

Battery Optimization Best Practices for Zero Compromise on Performance-New

 

The smartphones we own today are more powerful than before and boast hundreds of application to keep us entertained and informed but one thing we always desire is long lasting battery life to avoid getting disconnected from rest of the world.

 

The limitation of resources on mobile raise challenges for app developers majorly on battery consumption. This has led to concern and developers are continuously searching methods and tools to resolve the issue of optimizing energy consumption for the app.

 

As the display is moving towards higher resolution and increasing the screen size of the device battery power increment could not keep pace. Limiting the CPU utilization to the minimum possible, restricting the usage of radio and least network operations are not applicable in most of the scenarios. In this article, I will highlight the strategy to minimize the battery drainage with zero compromises on app performance and user experience.

 

  1. Limiting Battery Drain by Network: Smart use of networking hardware will ensure it doesn’t affect the battery drain negatively. A request made by an app to the network turns on power consuming mobile or Wi-Fi radios hence,   a common cause of battery drain.

 

 Limiting Battery Drain by Network

Image Credit: AndroidPolice

As smartphone radio need to communicate with cell towers for transferring a high volume of data there must be optimized first for restricting battery drain by sufficient amount which is evident from above image. Now as radio chip in most cases remains in power down state so need to wake up for data transfer when a request is made. The chip will remain active for few minutes waiting for server response. Each stage of radio cycle requires a different amount of battery and the maximum battery is used for waking the chip whenever a request is made and for the time it has to be awake. Now Network hardware optimization is directly related to how much data is transferred and when it is transferred.

 

When the networking task is user initiated app will respond immediately to respond to the user and upon running Battery Historian for the app you will find numerous red bars (indicating active state of mobile radio) and gaps between the bars (indicating inactive state of mobile radio) represent a serious performance issue on behalf of multiple active and inactive state. In order to resolve bunch the entire set of requests together and execute in a single large in the future instead of responding to the request each time on demand. This will drastically improve the battery efficiency. Instead of dealing with the complexity of doing it via coding prefer JobScheduler API to get the job done smoothly.

 

Job Scheduler API

Image Credit: SlideShare

If worried about how an app is consuming the networking resources then check Networking Profiling Tool in Android Studio to gain deeper insights how long request run and how much data they transfer.

 

2. Limiting Battery Drain by Location: Location information is an amazing feature of the mobile app that adds upto engaging user experience but ensuring it is not misused is important for avoiding unnecessary battery drain.

LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY

In the above location request, setInterval API defines the frequency at which your app will receive location updates. A lower numeral will bring more updates and eventually consume extra battery. Now a balanced value will determine neither it is fast enough that battery is drained by using it for handling multiple GPS requests nor too slow that app won’t update sufficiently fast and frustrate the user. Considering the fact that user might be at rest for some time or most of the time in some cases. SetFastestInterval API comes to rescue Android developers by enabling them to practice control over the frequency of updates thereby eliminating any scenarios of updating and processing location updates when not required. A battery efficient approach would be to control what sort of networking and battery drain to be used with help of     3. Limiting Battery Drain by Doze and App Standby: Ever wondered where does all power vanish from our devices? I agree power is continuously consumed while the screen is on and this consumption is way more than any other activity but, even when the screen is off it’s the CPU and networking radios that do the job of the user by consuming battery as below.

 

Activity

 

Image Credit: Android Developers

The three basics design principles that  are Reduce, Defer and Coalesce

 

Background activity

Image Credit: Android Developers

The logic is apps can batch together their background activity and coalesce them to improve the efficiency of the battery by substantially restricting the power consumption of the device. Doze is one such feature that will do it for you automatically. Doze will coalesce all power intensive background tasks. Based on device motion detectors doze will detect that device is unplugged and stationary with the screen off for quite some time.

 

Doze timeline

Image Credit: Android Developers

The thin orange stripes represent background tasks while orange bars are maintenance window and the green horizontal bars is the doze phase.

This will initiate the first phase of doze and make application free of Wakelocks, Network Access and stops any GPS activity or a WiFi scan. All the sync and alarms of these apps get deferred until next maintenance window (a short time period that coalesces all background tasks to perform pending background activity and refresh the data) this will strike a balance between battery power consumption and user expectation. The doze phase lasts for few hours.

 

App Standby is useful for optimizing the power consumption of apps that are not frequently used. Such applications lose network access and their syncs are deferred when the device is using the battery. Even on plugging in the device if the app is not used it will be considered standby and will lose network access on unplugging the device next time when it will be plugged in.

 

 

App Standby

Image Credit: Android Developers

The positive impact of Doze and App Standby is evident from the above data.

 

   4. Limiting Battery Drain by Monitoring the Battery Level and Charging State: Analyzing the existing battery level with charging state is an excellent choice to change the rate of background updates with the intention to reduce the battery drain thereby improving battery life by a significant percentage. 

 

 

The logical balance between a charging and unplugged device is that effect of updates while the device is being charged is far less rather negligible thereby providing you an opportunity to do more refresh rate. Unlike, if device battery is consumed by the various app you need to restrict the rate of the updates to avoid deteriorating battery health.

 

Charging Status for battery optimization

Image Credit: SlideShare

In order the ensure above logic you are required to determine the existing charging state. The below code will help you determine the current charge status.

 

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

Intent batteryStatus = context.registerReceiver(null, ifilter);

You can easily know both the current charging status and is the device charged via USB or AC charger.

// Are we charging / charged?

int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
      status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?

int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

 

It is advisable to maximize the frequency of your background updates especially when device is connected to a charger and restrict the rate if the charge is via USB but completely eliminate it when the battery is discharging.

 

   5. Limiting Battery Drain based on Connectivity State:  On behalf of the internet resources and cache data background services schedule updates to the applications. Such updates can negatively impact the battery life when the device has no internet connection or is on very slow internet connection. Such situation can be smartly handled by knowing the status of device connectivity with ConnectivityManager as well as determine the connection category to easily decide to continue with or restrict an update to an application.

Use below snippet for using the ConnectivityManager to query the active network and check it’s Internet connectivity.

 

ConnectivityManager cm =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                   NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();

 

  Connectivity ManagerImage Credit: SlidePlayer

Whether the device is connected via mobile data, WiMAX, Wi-Fi, or Ethernet can be known by inquiring the type of active network with below code snippet and accordingly switch to a refresh rate that has minimum impact on battery usage

boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

 

Since large updates tend to consume a huge amount of data hence, Wi-Fi can be preferred for such updates. The mobile connection will be more suitable for significantly smaller updates thereby, optimizing the updates for minimum or no negative impact on the battery health.

 

Hopefully, these strategic approaches encompassing different scenarios of battery optimization would certainly help you to design an app optimized for maximum battery usage without affecting the performance.

 

Being a big concern it’s the professional responsibility of an IT firm to ensure not only customized app on latest cutting edge technology to meet industry standards and make business objectives more than obvious but also to develop android apps that are optimized for minimum battery usage and a delightful user experience.

 

Related Posts...

AndroidMobile AppsTechnologies