Optimizing network, battery, and image use

Optimizing,Networking is one in every of the most important customers of battery. Optimizing your networking with the aid of following best practices will lessen battery drain, in addition to reducing the scale and frequency of information transfers.

In this realistic, you learn how to use tools to measure and analyze network and battery overall performance. You also learn how to compress pics to reduce the size of your information movement.

Optimizing network and battery overall performance is a large subject matter, and as devices alternate, so do some of the info and suggestions. The Android group is constantly improving the framework and APIs to make it easier with the intention to write apps that carry out well.

See the Best Practices: Network, Battery, Compression concept for an essential evaluation. Make use of the huge related assets to dive deeper and get the maximum updated pointers.

Optimizing,What you should already KNOW

You should be able to:

  • Create apps with Android Studio and run them on a cellular tool.
  • Work with Developer options on a mobile device.
  • Start the Android Profiler.

Optimizing,What you will LEARN

You will learn how to:

  • Monitor networking the use of the Networking Profiler tool.
  • Dump and view battery utilization the use of batterystats and Battery Historian 2.0.
  • Convert pictures to WebP format.

Optimizing,What you will DO

  • Run the Networking Profiler tool.
  • Dump battery information and display them as a chart the use of Battery Historian 2.0.
  • Convert an picture to WebP format the usage of Android Studio.

Optimizing,App overview

  • You’ll use the WhoWroteIt app, or any app of your preference that makes network calls.
  • You’ll create a simple demo app with a massive picture and an photo converted to WebP format.

Optimizing,Run the Network Profiler tool

Optimizing ,Android Profiler consists of the Network Profiler device, which makes it feasible to song when your app is making network requests in actual time. Using the Network Profiler, you can screen how and whilst your app transfers information. With this records, you may optimize your code to lessen the frequency of information transfers, and optimize the amount of statistics transferred all through every connection.

In this assignment you run Network Profiler with the WhoWroteIt app.

Optimizing ,Modify and run the WhoWroteIt app

  1. Download the WhoWroteIt app and open it in Android Studio.
  2. To help display the tools, adjust the MainActivity.SearchBooks() technique of the WhoWroteIt app:
  • Make more than one requires each seek. This will save you a few tedious on-screen typing.
  • Call the sleep() method among requests to make sure that every community call is made separately—that is, to ensure that the system does not batch the calls for you.

Obviously, you have to not do both of these items in a production app.

In the MainActivity.SearchBooks() approach, update this code:

// If the network is active and the search field is not empty, start a FetchBook AsyncTask.
if (networkInfo != null && networkInfo.isConnected() && queryString.length()!=0) {
new FetchBook(mTitleText, mAuthorText, mBookInput).execute(queryString);

With this code:

// If the network is active and the search field is not empty, start a FetchBook AsyncTask.
if (networkInfo != null && networkInfo.isConnected() && queryString.length()!=0) {
new FetchBook(mTitleText, mAuthorText, mBookInput).execute(queryString);
new FetchBook(mTitleText, mAuthorText, mBookInput).execute(queryString);
new FetchBook(mTitleText, mAuthorText, mBookInput).execute(queryString);
new FetchBook(mTitleText, mAuthorText, mBookInput).execute(queryString);
new FetchBook(mTitleText, mAuthorText, mBookInput).execute(queryString);

Run your app and perform one search. The app’s user interface has not changed, and you should see one search result for your query.

Optimizing network ,Run the Network Profiler tool

  1. On your tool, turn off Wi-Fi to ensure that your tool uses the cell radio for networking requests. Make sure that cell information is enabled on the device.
  2. Run your app on the tool. If feasible, do that on a physical device to get correct measurements.
  3. In Android Studio, open Android Profiler.
  4. Enter a book title in the app and click on the Search Books button. The Network Profiler ought to display a precis graph similar to the one under. The sample may also look distinct for one of a kind gadgets and network connections.
  • Orange spikes indicate facts despatched, and blue spikes records obtained. The WhoWroteIt app does now not ship loads of facts, so the orange spikes are short, while the blue spikes are a lot taller.
  • The horizontal axis movements in time, and the vertical axis suggests facts transfer price in kilobytes consistent with 2nd.
  • Every time your app makes a network request, a vertical spike on the Network Profiler shows the hobby.
  • The width of the bottom of the spike is how long the request took. The height of the spikes is the amount of statistics sent or received.
  1. Click the Network Profiler phase of the Android Profiler to make bigger the pane and notice extra information, as shown within the annotated screenshot below. To preserve the graph from transferring, click the Live button within the top-right nook of the profiler, or simply scroll lower back. Doing this doesn’t stop the recording.
  1. The horizontal colored bar at the top indicates whether the request changed into made on Wi-Fi (grey) or the cellular radio (dark or light blue). The energy nation of the cell radio is indicated by dark blue for high (the usage of extra battery strength) and light blue for low (using much less battery energy).
  2. Legend for type of radio used and strength state of cellular radio.
  3. The orange dotted line indicates the variety of lively connections over time, as shown on the y -axis on the right.
  4. The x -axis indicates the time that has surpassed.
  5. Orange spikes mark facts despatched. The width indicates how lengthy it took, and the height how a whole lot information changed into despatched. The WhoWroteIt app requests are small, so it does no longer take lengthy to send this small approximately of facts.
  6. Blue spikes mark records received. The width indicates how lengthy statistics wa obtained and the height how a lot facts changed into obtained. Depending on how many books match the request, the dimensions of the acquired statistics, and the way lengthy it takes to acquire it, can vary.
  7. The y -axis at the left suggests numeric values for the quantities of data in KB in step with 2d.
  8. Experiment with distinct queries to peer whether it slightly changes the community request styles.

Optimizing ,Network Profiler details

Optimizing ,To display you superior profiling records, Android Studio need to inject tracking common sense into your compiled app. Features furnished with the aid of advanced profiling consist of:

  • The event timeline on all profiler home windows
  • The variety of allocated gadgets inside the Memory Profiler device
  • Garbage collection events inside the Memory Profiler tool
  • Details approximately all transmitted files in the Network Profiler tool

To enable the advanced profiling in Android Studio, follow these steps:

  • Select Run > Edit Configurations.
  • Select your app module in the left pane.
  • Click the Profiling tab, after which select Enable superior profiling.
  • Now construct and run your app once more to get entry to the entire set of profiling features. Advanced profiling slows your construct pace, so permit it most effective when you need to start profiling your app.
  • Open the Android Profiler tab.
  • Click at the Network Profiler graph to open the detail view, then click on on it once more to open the advanced profiling panes.
  • On your connected mobile device, look for a book to get facts shifting over the network and generate a graph. The example below uses a question for the word “jungle”.

Refer to the annotated screenshot below for the next steps.

  • Scroll lower back the graph to prevent actual-time viewing.
  • Note the red dot at the top of the pane (1), which indicates a person movement. In this situation, the motion was pressing the Search Books button.
  • Next to the user motion, you see the payload in your request, which in this case consists of the phrase “jungle” (2).
  • Select a portion of the graph to get greater details about it (3).
  • A pane opens beneath the graph listing all the requests and responses with additional information inside the decided on portion of the graph (4).
  • Click on a request, and a new pane with 3 tabs opens (five). By default, you notice the contents of the first tab, displaying the contents of the response (6).
  • In the screenshot above, word that the blue bar above the selected portion of the graph remains darkish, indicating that the radio is in a excessive-electricity kingdom all through the requests. This is because the requests observe each other carefully enough to maintain the radio on.
  • In the WhoWroteIt app, alternate the sleep time for one of the requests till the radio powers off between requests. How lengthy the cellular radio stays within the excessive kingdom can range substantially between gadgets.
  • In the screenshot underneath, after a request, the radio is in the excessive-electricity country (1). The radio stays within the excessive-electricity nation for almost 30 seconds before powering down (2). Then the radio powers up again for the next request (3).
  • Click the Call Stack tab to peer where the request originated on your code. When your app makes many extraordinary styles of network requests, the Call Stack tab facilitates you pinpoint where to your code you can need to begin optimizing.

When sending requests and receiving responses, try to optimize for energy intake of the cellular radio by means of minimizing the time the mobile radio is in a high-power state. This can be tough, and a full rationalization is past the scope of this practical. However, right here are some recommendations to get you started out.

  • Limit the scale of your requests and responses. Formulate your queries to best request the records you in reality want.
  • Batch your requests so you can ship several of them together at once to take benefit of the excessive-energy nation. Space the sending of requests to maximize for the cell radio staying in decrease power states.

For more satisfactory practices, see Optimizing Battery Life and the Best Practices: Network, Battery, Compression idea.

Optimizing,Run battery statistics and visualization tools

Optimizing ,Dumpsys is an Android device that runs at the cellular device and dumps interesting records about the popularity of machine offerings as you operate the device. The dumpsys command retrieves this facts from the device so that you can use it to debug and optimize your app.

You used dumpsys framestats within the Systrace and dumpsys realistic.

Batterystats collects battery information from your device, and the Battery Historian tool converts that records into an HTML visualization that you may view to your browser. Batterystats is a part of the Android framework, and the Battery Historian tool is open-sourced and to be had on GitHub. Batterystats shows you wherein and the way approaches are drawing present day from the battery, and it enables you pick out duties for your app that would be deferred or maybe removed to improve battery existence.

You can use the Battery Historian device at the output of the dumpsys command to generate a visualization of strength-related activities from the device logs, as proven within the screenshot under. This facts makes it less complicated in order to understand and diagnose battery-related issues. Battery Historian isn’t a part of the Android framework, and you’ll want to down load and install it from the net.

In this sensible, you create and paintings with a Battery Historian chart.

Warning:Installing the Docker and Battery Historian equipment requires downloading approximately 500 MB of data on your neighborhood pc, which may also take the time. Make positive that you have enough time, bandwidth, and disk area earlier than you begin.
Important: Use the Chrome browser to work with Battery Historian files.

nstall the Docker software management platform

The Battery Historian device is open sourced and to be had on GitHub.

There are special ways to put in the device. Using Docker is by way of a ways the very best. Docker is an open platform for builders and system directors to build, ship, and run distributed apps. See the README.Md report with the Battery Historian supply code on GitHub for greater installation alternatives and documentation.

To deploy and installation Docker:

  • On your computer, installation the unfastened network edition of Docker from https://www.Docker.Com/community-version.
  • Start Docker. This may additionally make an effort, because greater components will down load.
  • Once Docker is prepared, open a terminal window in Android Studio or in your computing device.
  • Enter the following instructions within the terminal to verify that Docker is installed, going for walks, and working well:
docker --version 
  docker ps
  docker run hello-world

Read Docker’s output, as it summarizes how Docker works.

docker run hello-world
 Unable to find image 'hello-world:latest' locally
 latest: Pulling from library/hello-world
 78445dd45222: Pull complete 
 Digest: sha256:c5515758d4c5e1e838e9cd307f6c6a0d620b5e07e6f927b07d05f6d12a1ac8d7
 Status: Downloaded newer image for hello-world:latest

 Hello from Docker!
 This message shows that your installation appears to be working correctly.

 To generate this message, Docker took the following steps:
  1. The Docker client contacted the Docker daemon.
  2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
  3. The Docker daemon created a new container from that image which runs the
     executable that produces the output you are currently reading.
  4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal.

Get the Battery Historian tool

Run the following Docker command.

docker run -p 1234:9999 gcr.io/android-battery-historian/stable:3.0 --port 9999

1234 is the port number for Battery Historian in your localhost. You can replace 1234 with the port number of your desire. (This may pull the Battery Historian, which may take a while depending in your net pace.)

Important:Check the READMEfile for Battery Historian in GitHub for the brand new model wide variety, because the device gets up to date and advanced.

You will see a series of messages in the terminal, similar to the following:

Unable to find image 'gcr.io/android-battery-historian/stable:3.0' locally
3.0: Pulling from android-battery-historian/stable
c62795f78da9: Downloading 12.84 MB/45.56 MB
d4fceeeb758e: Download complete 
e06a9fa76cf2: Pull complete 
Digest: sha256:265a37707f8cf25f2f85afe3dff31c760d44bb922f64bbc455a4589889d3fe91
Status: Downloaded newer image for gcr.io/android-battery-historian/stable:3.0
2017/08/04 18:33:34 Listening on port:  9999

Do not close the terminal or terminate the terminal window, because this will stop Battery Historian.

Linux and Mac OS X:

  • That’s it. Open Battery Historian, to be able to be to be had in your browser at http://localhost:1234/


  • You might also need to allow virtualization. If you’re capable of run the emulator with Android Studio, then virtualization is already enabled.
  • Once you begin Docker, it need to let you know the IP address of the system it is the usage of. If, for instance, the IP cope with is 123.456.Seventy eight.90, Battery Historian can be available at http://123.456.Seventy eight.90:1234. (If you used a exceptional port, alternative it within the URL.)

Run commands to get battery statistics

Your mobile device collects statistics about itself as it runs. This information is useful for debugging as well as performance analysis. The dumpsys batterystats command gets information related to battery usage from your device.

  • Connect your cellular tool on your computer.
  • Turn off device Wi-Fi in order that the tool makes use of the mobile radio.
  • If you have not already done so, down load the WhoWroteIt app and open it in Android Studio.
  • Run the WhoWroteIt app in your mobile tool.
  • On your pc, open a terminal window. (Use the command activate on a Windows system, or open the Terminal pane in Android Studio.)
  • From the command line, close down your going for walks adb server.
 adb kill-server
  • Restart adb and check for connected devices. The command lists any connected devices.
 $ adb devices
  List of devices attached
  emulator-5554        device
  LGH918ce000b4b        device
  • Reset battery data gathering. Resetting erases old battery collection data; otherwise, the output from the dump command will be huge.
 adb shell dumpsys batterystats --reset
  • Disconnect your cell device out of your laptop so that you are best drawing electricity from the tool’s battery. On the emulator, you will now not get accurate statistics for this workout.
  • Play with the WhoWroteIt app for a brief time. Search for different books via using unique seek text.
  • Reconnect your cell device.
  • On your cellular device, turn Wi-Fi on.
  • Make positive that adb acknowledges your cell tool.
adb devices
  • Dump all battery data and redirect the output to save it into a text file. This can take a while.
adb shell dumpsys batterystats > batterystats.txt
  • To create a report from raw data on a device running Android 7.0 and higher:
adb bugreport bugreport.zip

For devices 6.0 and lower:

adb bugreport > bugreport.txt

Bugreport ought to take numerous minutes to finish. Do now not cancel, close the terminal window, or disconnect your tool till it is done.

  • On the Battery Historian beginning page on your Chrome browser (see previous screenshot), browse for the bugreport.Txt or bugreport.Zip record. Click Submit to upload and show the chart. If you used Terminal pane in Android Studio, the bugreport file will be located in the WhoWroteIt app’s root directory.

What you see in the Battery Historian chart

The Battery Historian chart graphs power-applicable occasions over the years.

Each row suggests a colored bar phase when a gadget thing is lively and drawing present day from the battery. The chart does no longer display how a great deal battery was used by the factor, best that the app was energetic.

  • Hover over the bars to get details about each graph. You will work more with this in a minute.
  • Hover over the “i” information icon on the left to get a color legend, as shown in the figure below.
  • Using the chart screenshot under and reasons under, discover your chart. Your chart appears unique than the screenshot because you are on a special tool, and you probable finished special movements.

Chart guidelines

The following chart shows three minutes of information for an LG V20 mobile device running the modified WhoWroteIt app.

The numbers inside the following listing reference the numbered callouts within the picture underneath, illustrating a number of the powerful information you may collect and analyze.

  • (1) The Mobile radio active line indicates the hobby of the mobile radio. The cellular radio is one in every of the largest battery users. When working on battery efficiency, you always need to take a look at and optimize the cellular radio’s pastime.
  • (2) Movable timeline that shows records about battery rate kingdom. The top container shows data approximately the contemporary battery country. The bottom bars show that the tool became no longer plugged in at this second, and it became no longer charging. This data is useful while you need to confirm that your code most effective plays sure battery in depth activities, along with syncs, while the device is plugged in and on Wi-Fi.
  • (3) Mobile radio interest. The selected bar inside the Mobile radio active line, and those nearby, are in all likelihood the WhoWroteIt app’s network calls to fetch books. The information field for the bar below the timeline marker shows extra information which includes the duration and the variety of occurrences.

See the following documentation for more:

Convert images to WebP format

Most down load visitors consists of photos fetched from a server. The smaller you may make your downloadable snap shots, the better the network enjoy your app can provide for customers. Downloading smaller photos method faster downloads, much less time at the radio, and capability savings of battery energy. Using WebP snap shots together with your app sources reduces APK size, which in turn manner faster app downloads for your users.

WebP is an picture document layout from Google. WebP provides lossy compression (as JPG does) and transparency (as PNG does), however WebP can offer higher compression than either JPG or PNG. A WebP file is regularly smaller in size than its PNG and JPG opposite numbers, with at least the identical photograph best. Even the use of lossy settings, WebP can produce a nearly equal picture to the original. Android has covered lossy WebP aid considering the fact that Android four.0 (API 14) and support for lossless, obvious WebP on the grounds that Android four.3 (API 18).

Serve WebP files over the network to reduce photo load times and shop community bandwidth.

In fashionable, use the following algorithm to determine which photograph layout to use:

Do you support WebP? 
        Yes: Use WebP
        No: Does it need transparency?
                Yes: Use PNG
                No: Is the image "simple" (colors, structure, subject?)
                       Yes: Use PNG
                        No: Use JPG

Create an app and compare image sizes and quality for different formats

Android has covered lossy WebP help considering that Android 4.0 (API 14) and guide for lossless, transparent WebP in view that Android 4.2 (API 18).

Support for lossless and transparent WebP pics is best to be had in Android 4.2 and better. That approach your task have to claim a minSdkVersion of 18 or better to create lossless or transparent WebP photos the use of Android Studio.

Note:You can create a brand new app for this venture, or you may make a duplicate of the LargeImages app and modify it in accordance with the stairs underneath.
  • Create an app with a minSdkVersion of 18 the usage of the Basic Template.
  • Add the identical massive photo which you used in the LargeImages app because the background for the textual content view.
  • Make a backup copy of the image in res/drawable. You need the backup because conversion happens in place, changing your original photograph.
  • In your res/drawable folder, right-click the photo and select Convert to WebP at the bottom of the menu. The Convert Images to WebP conversation opens.
  • This conversion happens “in-area”; this is, your original photo is modified into the compressed image.
  • Choose Lossy encoding, flow the slider to 21%, and click on OK to preview the documents. For this precise picture, these settings will provide you with approximately 10% of the scale for the transformed image. This saves you over 350 K!
  • Click Finish to keep the transformed small picture and rename it to mnt_diablo_webp.Webp.
  • Add an onClick() handler to the text view that swaps the background between the sponsored up authentic and the WebP photo.
  • Run your app.
  • Click to swap between the two pics. Do you word any distinction in excellent? In maximum cases the distinction need to be unnoticeable to casual user.


  • Network Monitor gives you a brief live observe how your app is making community requests.
  • The dumpsys batterystats command receives battery-related facts out of your cellular tool.
  • The Battery Historian device presentations the batterystats information as an interactive time chart. You can use the chart to correlate battery utilization with sports taken by using your app.