SlideShare a Scribd company logo
Optimizing Apps for Better
Performance
Elif Boncuk
Software Specialist @ Garanti Teknoloji
Who am I?
➢Hacettepe - Computer Engineering (2006 - 2011)
➢Garanti Technology - Mobile Applications Team (2011- )
➢MBA Student @BAU (2014 - )
➢GDG Istanbul
➢WTM Istanbul
➢Blogger (2010 - )
➢Photographer
@elifbon_
www.elifboncuk.wordpress.com
elifboncuk88@gmail.com
Be Faster!
➢Gather Information
➢Gain Insight
➢Take Action
4 Major Steps
➢Rendering
➢Compute
➢Memory
➢Battery
Rendering
Rendering...
Rendering...
MEASURE
EXECUTE
RECORD
LAYOUT
CPU
RASTERIZATION GPU
F
L
O
W
PROBLEM
PROBLEM OVERDRAW
LAYOUTS &
INVALIDATIONS
Rasterization
Overdraw
➢Overdraw is a term used to describe how many times a pixel on the screen has been redrawn in
a single frame.
Overdraw...
1. On your mobile device, go to Settings and tap Developer Options.
2. In the Hardware accelerated rendering section, select Debug GPU
Overdraw.
3. In the Debug GPU overdraw popup, select Show overdraw areas.
4. Don't panic as your screen turns into a delirium of colors. The coloring
is provided to help you diagnose your app's display behavior.
Overdraw…
5. The colors are hinting at the amount of overdraw on your screen
for each pixel, as follows:
True color: No overdraw
Blue: Overdrawn once
Green: Overdrawn twice
Pink: Overdrawn three times
Red: Overdrawn four or more times
Overdraw…
How?
➢Eliminate unneeded backgrounds and
drawables
➢Define areas will hide portions of view
➢Use RelativeLayout instead of LinearLayout
Best Practices:
➢getWindow().setBackgroundDrawable(null
➢android:background:”@null”
Clipping
➢Clipping is an optimisation which can be defined as Android
framework knows overdraw is a problem and will go out of its
way to avoid drawing UI widgets that may be invisible in the final
image.
➢Canvas.quickReject()
➢Canvas.clipRect()
DRAWABLE
ZONE
Canvas.clipRect()
20dp
20dp 20dp
20dp
Clipping
Clipping
Q: Bu seviyede overdraw yaşanmasına ne sebep olmuş olabilir?
1- Dikkatsiz kod yazarak, çok fazla sayıda background tanımlamış olabiliriz.
2- Kartları ekrana bazı parçaları hidden, birbirinin üstünü örtecek şekilde çizmiş olabiliriz.
3- Bu senaryoda Custom View kullanmamalıydık.
Clipping
Clipping
CPU Optimizations
Hierarchy Viewer
ANDROID_HVPROTO
○ http://developer.android.com/tools/performance/hierarchy-viewer/setup.html
ViewServer
○ https://github.com/romainguy/ViewServer
Register when created
Unregister when destroyed
Hierarchy Viewer
Hierarchy Viewer
Bird's-eye view
Tree Overview
Tree View
View Properties
Nodes
Hierarchy Viewer
Each view in your subtree gets three dots, which
can be green, yellow, or red.
The left dot represents the Draw Process of the
rendering pipeline.
The middle dot represents the Layout Phase.
The right dot represents the Execute Phase.
Hierarchy Viewer
The color of the dots indicates the relative performance of this node
in respect to all other profiled nodes.
Green means the view renders faster than at least half of the other
views.
Yellow means the view renders faster than the bottom half of the
other views.
Red means the view is among the slowest half of views.
Hierarchy Viewer
https://github.com/ElifBon/HierarchyViewerSample
Hierarchy Viewer
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com
/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<ImageView
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<RelativeLayout
android:layout_width="100dp"
android:layout_height="wrap_content"
android:paddingLeft="16dp">
<ImageView
android:id="@+id/colorImage"
android:layout_width="80dp"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="@android:color/holo_green_dark" />
<TextView
android:id="@+id/year"
android:layout_width="80dp"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"/>
<TextView
android:id="@+id/day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/year"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
Hierarchy Viewer
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_gravity="center" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/photo"
android:paddingLeft="16dp" />
<TextView
android:id="@+id/place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/photo"
android:layout_below="@id/name"
android:paddingLeft="16dp" />
<TextView
android:id="@+id/year"
android:layout_width="80dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:background="@android:color/holo_green_dark"
android:gravity="center" />
<TextView
android:id="@+id/day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/year"
android:layout_alignParentRight="true"
android:layout_below="@+id/year"
android:layout_marginLeft="16dp" />
</RelativeLayout>
Hierarchy Viewer
Hierarchy Viewer
Hierarchy Viewer
https://youtu.be/kMUYOnD0Tqc
Rendering - Tips & Tricks
● getWindow().setBackgroundDrawable(null); // Temadan aldığı renkle aynıysa bu gereksiz
● android:background:”@null” // xml
● Canvas.clipRect();
● Canvas.quickReject();
● Flat hiyerarchy
● Gereksiz layoutlardan kaçının
● Use RelativeLayout instead of LinearLayout
Compute
➢Slow Function Performance
Profiling with Traceview
➢Traceview is a graphical viewer for execution logs that you create by using the Debug class to log
tracing information in your code. Traceview can help you debug your application and profile its
performance.
Profiling with Traceview
Profiling with Traceview
The Timeline pane visualizes how your
code executes over time.
Each row shows a thread.
Each bar on the timeline is a method
executing.
Each color is for a different method;
every time a method executes, you
see a the same color bar.
The width of its bar indicates how long
the method takes to execute.
The Profiling pane shows a list of methods.
Select a method to see who called it (Parent) and who it's calling
(Children).
The selected method is also highlighted in theTimeline pane.
The columns show exclusive and inclusive CPU and real times,
percentages, ratios, and how often a method was called.
The exclusive time is the time spent just in the method itself, which can
help you find issues within that specific method.
The inclusive time is for the method and all methods it calls, which can
help you find problems with your call tree.
The Calls+Rec column shows how many times a method was called
recursively, which can help you track down performance issues.
Batching and Caching
Caching for Networking
Caching HTTP
Responses is
disabled by
Default.
https://www.youtube.com/watch?v=7lxVqqWwTb0&list=PLOU2XLYxmsIKEOXh5TwZEv89aofHzNCiu&index=1
Caching for Networking
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
try{
File httpCacheDir = new File(getBaseContext().getCacheDir(),"http");
long httpCacheSize = 10*1024*1024; //10Mib
HttpResponseCache.install(httpCacheDir, httpCacheSize);
}catch (IOException e){
Log.i(TAG, "HTTP response cache installation failed." + e.getMessage());
}
}
@Override
protected void onStop() {
super.onStop();
...
HttpResponseCache cache = HttpResponseCache.getInstalled();
if(null != cache){
cache.flush();
}
}
Caching for Networking
Caching for Networking
Force a Network Response:
Force a Cache Response:
http://developer.android.com/reference/android/net/http/HttpResponseCache.html
Caching for Networking
Caching for Networking
http://developer.android.com/samples/DisplayingBitmaps/src/com.example.android.displayingbitmaps/util/DiskLruCache.html
● Volley
● okHTTP
● Picasso
Blocking the UI Thread
How to Solve?
Android's single thread model:
1. Do not block the UI thread
2. Do not access the Android UI toolkit
from outside the UI thread
How to Solve?
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap bitmap =
loadImageFromNetwork("http://example.com/image.png")
;
mImageView.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}
}).start();
}
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b =
loadImageFromNetwork("http://example.com/image.p
ng");
mImageView.setImageBitmap(b);
}
}).start();
}
How to Solve?
public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
Analyzing UI Performance with Systrace
➢The Systrace tool allows you to collect and inspect timing information across an entire Android
device, which is called a trace.
➢As simply, you should put your code that you want to trace between this two lines.
Trace.beginSection("Data Structures");
// TODO:
Trace.endSection();
Analyzing UI Performance with Systrace
Bad Performance Example
Analyzing UI Performance with Systrace
Analyzing UI Performance with Systrace
Memory
Basic Prinsiples of Garbage Collection:
➢Find data objects in a program that cannot be accesed in the future.
➢Reclaim the resources used by those objects.
Memory Monitor
Memory Monitor reports in real-time how your app allocates memory.
➢Showing available and used memory in a graph, and garbage collection events over time.
➢Quickly testing whether app slowness might be related to excessive garbage collection events.
➢Quickly testing whether app crashes may be related to running out of memory.
Dark blue: Amount of memory that your app is currently using.
Light blue: Available, unallocated memory.
Memory Monitor
Heap Viewer
Heap Viewer reports in real-time what types of objects your application has allocated, how many,
and their sizes on the heap.
➢Getting a sense of how your app allocates and frees memory.
➢Identifying memory leaks.
➢5.0+
Heap Viewer
Allocation Tracker
Allocation Tracker records an app's memory allocations and lists all allocated objects for the profiling cycle with their call
stack, size, and allocating code.
➢Identifying where many similar object types, from roughly the same call stack, are allocated and deallocated over a very
short period of time.
➢Finding the places in your code that may contribute to inefficient memory use.
How your app should manage memory
➢ Use services sparingly
➢ Release memory when your user interface becomes hidden
➢ Release memory as memory becomes tight
➢ Check how much memory you should use
➢ Avoid wasting memory with bitmaps
➢ Use optimized data containers
➢ Be aware of memory overhead
➢ Be careful with code abstractions
➢ Use nano protobufs for serialized data
➢ Avoid dependency injection frameworks
➢ Be careful about using external libraries
➢ Optimize overall performance
➢ Use ProGuard to strip out any unneeded code
http://developer.android.com/training/articles/memory.html
Battery
Batterystats & Battery Historian
Batterystats collects battery data from your device, and Battery Historian converts that data into an HTML
visualization that you can view in your Browser.
➢Showing you where and how processes are drawing current from the battery.
➢Identifying tasks in your app that could be deferred or even removed to improve battery life.
➢5.0+
Batterystats & Battery Historian
Batterystats & Battery Historian
battery_level: When the battery level was recorded and logged.
top: The application running at the top.
wifi_running: Shows that the Wi-Fi network connection was active.
screen: Screen is turned on.
phone_in_call: Recorded when the phone is in a call.
wake_lock: App wakes up, grabs a lock, does small work, then goes back to sleep. Trunning: Shows when the CPU is
awake. Check whether it is awake and asleep when you expect it to be.
wake_reason: The last thing that caused the kernel to wake up. If it's your app, determine whether it was necessary.
mobile_radio: Shows when the radio was on. Starting the radio is battery expensive. Many narrow bars close to each
other can indicate opportunities for batching and other optimizations.
gps: Indicates when the GPS was on. Make sure this is what you expect.
Batterystats & Battery Historian
Battery History: A time series of power-relevant events, such as screen, Wi-Fi, and
app launch. These are also visible through Battery Historian.
Per-PID Stats: How long each process ran.
Statistics since last charge: System-wide statistics, such as cell signal levels and
screen brightness. Provides an overall picture of what's happening with the device.
This information is especially useful to make sure no external events are affecting
your experiment.
Estimated power use (mAh) by UID and peripheral: This is currently an extremely
rough estimate and should not be considered experiment data.
Per-app mobile ms per packet: Radio-awake-time divided by packets sent. An
efficient app will transfer all its traffic in batches, so the lower this number the better.
All partial wake locks: All app-held wakelocks, by aggregate duration and count.
Optimizing Network Request Frequencies
Optimizing Network Request Frequencies
Adapting to Latency
Adapting to Latency
ConnectivityManager cm =
(ConnectivityManager)getBaseContext().getSystemService(Context.CONNE
CTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork.getType() != ConnectivityManager.TYPE_WIFI){
String typeName = activeNetwork.getSubtypeName();
int type = activeNetwork.getSubtype();
switch (type){
// TelephonyManager.NETWORK_TYPE *enums
}
}
Adapting to Latency
Adapting to Latency
● Emulator Throttling
● Network Attenuator
Batterystats & Battery Historian
Wakelock API
private void pollServer() {
mWakeLockMsg.setText("Polling the server! This day sure went by fast.");
for (int i=0; i<10; i++) {
mWakeLock.acquire();
mWakeLockMsg.append("Connection attempt, take " + i + ":n");
mWakeLockMsg.append(getString(R.string.wakelock_acquired));
// Always check that the network is available before trying to connect. You don't want
// to break things and embarrass yourself.
if (isNetworkConnected()) {
new SimpleDownloadTask().execute();
} else {
mWakeLockMsg.append("No connection on job " + i + "; SAD FACE");
}
}
}
@Override
protected void onPostExecute(String result) {
mWakeLockMsg.append("n" + result + "n");
releaseWakeLock();
}
JobScheduler
mServiceComponent = new ComponentName(this,
MyJobService.class);
@Override
public boolean onStartJob(JobParameters params) {
Log.i(LOG_TAG, "Totally and completely working
on job " + params.getJobId());
// First, check the network, and then attempt to
connect.
if (isNetworkConnected()) {
new SimpleDownloadTask() .execute(params);
return true;
} else {
Log.i(LOG_TAG, "No connection on job " +
params.getJobId() + "; sad face");
}
return false;
}
public void pollServer() {
JobScheduler scheduler = (JobScheduler)
getSystemService(Context.JOB_SCHEDULER_SERVICE);
for (int i=0; i<10; i++) {
JobInfo jobInfo = new JobInfo.Builder(i,
mServiceComponent)
.setMinimumLatency(5000) // 5
seconds
.setOverrideDeadline(60000) // 60
seconds (for brevity in the sample)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
// WiFi or data connections
.build();
mWakeLockMsg.append("Scheduling job " + i +
"!n");
scheduler.schedule(jobInfo);
}
}
Lint
http://developer.android.com/tools/debugging/improving-w-lint.html
Lint
https://www.youtube.com/watch?v=Z_huaXCsYyw&index=36&list=PLOU2XLYxmsIKEOXh5TwZEv89aofHzNCiu
Lint
Lint
Questions?
@elifbon_
+ElifBoncuk
www.elifboncuk.wordpress.com
elifboncuk88@gmail.com - elifbon@garanti.com.tr
Thank you!

More Related Content

What's hot

Y1 gd engine_terminology
Y1 gd engine_terminologyY1 gd engine_terminology
Y1 gd engine_terminology
Ben_Atherton
 
Harry Johnson y1 gd engine_terminology
Harry Johnson y1 gd engine_terminologyHarry Johnson y1 gd engine_terminology
Harry Johnson y1 gd engine_terminology
11275449
 
Y1 js engine_terminology
Y1 js engine_terminologyY1 js engine_terminology
Y1 js engine_terminology
JamieShepherd
 
Android Applications Development: A Quick Start Guide
Android Applications Development: A Quick Start GuideAndroid Applications Development: A Quick Start Guide
Android Applications Development: A Quick Start Guide
Sergii Zhuk
 
[1D6]RE-view of Android L developer PRE-view
[1D6]RE-view of Android L developer PRE-view[1D6]RE-view of Android L developer PRE-view
[1D6]RE-view of Android L developer PRE-view
NAVER D2
 
Researched definition 9
Researched definition 9Researched definition 9
Researched definition 9
tommo123456
 
Lewis brady engine terminology (edited version)
Lewis brady engine terminology (edited version)Lewis brady engine terminology (edited version)
Lewis brady engine terminology (edited version)
LewisB2013
 
Android App development and test environment, Understaing android app structure
Android App development and test environment, Understaing android app structureAndroid App development and test environment, Understaing android app structure
Android App development and test environment, Understaing android app structure
Vijay Rastogi
 
Anthony newman y1 gd engine_terminologyvvvvv
Anthony newman y1 gd engine_terminologyvvvvvAnthony newman y1 gd engine_terminologyvvvvv
Anthony newman y1 gd engine_terminologyvvvvv
anthonynewman
 
Y1 gd engine terminology
Y1 gd engine terminologyY1 gd engine terminology
Y1 gd engine terminology
KeatonBradley
 
Cameron mc rae y1 gd_engineterminology no videos
Cameron mc rae y1 gd_engineterminology no videosCameron mc rae y1 gd_engineterminology no videos
Cameron mc rae y1 gd_engineterminology no videos
CameronMcRae901
 
Using a 3D Game Engine
Using a 3D Game EngineUsing a 3D Game Engine
Using a 3D Game Engine
ItsLiamOven
 
Gamedesign Task 1 for Ian by Liam Oven
Gamedesign Task 1 for Ian by Liam OvenGamedesign Task 1 for Ian by Liam Oven
Gamedesign Task 1 for Ian by Liam Oven
ItsLiamOven
 
Anthony Bowes task 1 IG unit 70
Anthony Bowes task 1 IG unit 70Anthony Bowes task 1 IG unit 70
Anthony Bowes task 1 IG unit 70
bowes96123
 
Y1 gd engine_terminology ig2 game engines
Y1 gd engine_terminology ig2 game enginesY1 gd engine_terminology ig2 game engines
Y1 gd engine_terminology ig2 game engines
Lewis Brierley
 
Y1 gd engine_terminology ig2 game engines
Y1 gd engine_terminology ig2 game enginesY1 gd engine_terminology ig2 game engines
Y1 gd engine_terminology ig2 game engines
Lewis Brierley
 
Y1 gd engine_terminology amy brockbank
Y1 gd engine_terminology amy brockbankY1 gd engine_terminology amy brockbank
Y1 gd engine_terminology amy brockbank
amybrockbank
 

What's hot (17)

Y1 gd engine_terminology
Y1 gd engine_terminologyY1 gd engine_terminology
Y1 gd engine_terminology
 
Harry Johnson y1 gd engine_terminology
Harry Johnson y1 gd engine_terminologyHarry Johnson y1 gd engine_terminology
Harry Johnson y1 gd engine_terminology
 
Y1 js engine_terminology
Y1 js engine_terminologyY1 js engine_terminology
Y1 js engine_terminology
 
Android Applications Development: A Quick Start Guide
Android Applications Development: A Quick Start GuideAndroid Applications Development: A Quick Start Guide
Android Applications Development: A Quick Start Guide
 
[1D6]RE-view of Android L developer PRE-view
[1D6]RE-view of Android L developer PRE-view[1D6]RE-view of Android L developer PRE-view
[1D6]RE-view of Android L developer PRE-view
 
Researched definition 9
Researched definition 9Researched definition 9
Researched definition 9
 
Lewis brady engine terminology (edited version)
Lewis brady engine terminology (edited version)Lewis brady engine terminology (edited version)
Lewis brady engine terminology (edited version)
 
Android App development and test environment, Understaing android app structure
Android App development and test environment, Understaing android app structureAndroid App development and test environment, Understaing android app structure
Android App development and test environment, Understaing android app structure
 
Anthony newman y1 gd engine_terminologyvvvvv
Anthony newman y1 gd engine_terminologyvvvvvAnthony newman y1 gd engine_terminologyvvvvv
Anthony newman y1 gd engine_terminologyvvvvv
 
Y1 gd engine terminology
Y1 gd engine terminologyY1 gd engine terminology
Y1 gd engine terminology
 
Cameron mc rae y1 gd_engineterminology no videos
Cameron mc rae y1 gd_engineterminology no videosCameron mc rae y1 gd_engineterminology no videos
Cameron mc rae y1 gd_engineterminology no videos
 
Using a 3D Game Engine
Using a 3D Game EngineUsing a 3D Game Engine
Using a 3D Game Engine
 
Gamedesign Task 1 for Ian by Liam Oven
Gamedesign Task 1 for Ian by Liam OvenGamedesign Task 1 for Ian by Liam Oven
Gamedesign Task 1 for Ian by Liam Oven
 
Anthony Bowes task 1 IG unit 70
Anthony Bowes task 1 IG unit 70Anthony Bowes task 1 IG unit 70
Anthony Bowes task 1 IG unit 70
 
Y1 gd engine_terminology ig2 game engines
Y1 gd engine_terminology ig2 game enginesY1 gd engine_terminology ig2 game engines
Y1 gd engine_terminology ig2 game engines
 
Y1 gd engine_terminology ig2 game engines
Y1 gd engine_terminology ig2 game enginesY1 gd engine_terminology ig2 game engines
Y1 gd engine_terminology ig2 game engines
 
Y1 gd engine_terminology amy brockbank
Y1 gd engine_terminology amy brockbankY1 gd engine_terminology amy brockbank
Y1 gd engine_terminology amy brockbank
 

Viewers also liked

Project Analysis - How to Start Project Develoment
Project Analysis - How to Start Project DevelomentProject Analysis - How to Start Project Develoment
Project Analysis - How to Start Project Develoment
Adarsh Patel
 
Workhsop on Logic Building for Programming
Workhsop on Logic Building for ProgrammingWorkhsop on Logic Building for Programming
Workhsop on Logic Building for Programming
Adarsh Patel
 
Workshop on Search Engine Optimization
Workshop on Search Engine OptimizationWorkshop on Search Engine Optimization
Workshop on Search Engine Optimization
Adarsh Patel
 
App indexing api
App indexing apiApp indexing api
App indexing api
Mohammad Tarek
 
Hack'n Break Android Workshop
Hack'n Break Android WorkshopHack'n Break Android Workshop
Hack'n Break Android Workshop
Elif Boncuk
 
Lecture 04. Mobile App Design
Lecture 04. Mobile App DesignLecture 04. Mobile App Design
Lecture 04. Mobile App Design
Maksym Davydov
 
Android development session 3 - layout
Android development   session 3 - layoutAndroid development   session 3 - layout
Android development session 3 - layout
Farabi Technology Middle East
 
What's new in Android at I/O'16
What's new in Android at I/O'16What's new in Android at I/O'16
What's new in Android at I/O'16
Elif Boncuk
 
Overview of DroidCon UK 2015
Overview of DroidCon UK 2015 Overview of DroidCon UK 2015
Overview of DroidCon UK 2015
Elif Boncuk
 
Android Udacity Study group 1
Android Udacity Study group 1Android Udacity Study group 1
Android Udacity Study group 1
Aly Abdelkareem
 
Android development session 4 - Fragments
Android development   session 4 - FragmentsAndroid development   session 4 - Fragments
Android development session 4 - Fragments
Farabi Technology Middle East
 
Fundamental of android
Fundamental of androidFundamental of android
Fundamental of android
Adarsh Patel
 
Working better together designers &amp; developers
Working better together   designers &amp; developersWorking better together   designers &amp; developers
Working better together designers &amp; developers
Vitali Pekelis
 
Workshop Android for Java Developers
Workshop Android for Java DevelopersWorkshop Android for Java Developers
Workshop Android for Java Developers
mhant
 
Session #8 adding magic to your app
Session #8  adding magic to your appSession #8  adding magic to your app
Session #8 adding magic to your app
Vitali Pekelis
 
Management Innovation
Management Innovation Management Innovation
Management Innovation
Elif Boncuk
 
Lecture 06. iOS Programming. Основи Objective-C
Lecture 06. iOS Programming. Основи Objective-CLecture 06. iOS Programming. Основи Objective-C
Lecture 06. iOS Programming. Основи Objective-C
Maksym Davydov
 
Android Development Workshop
Android Development WorkshopAndroid Development Workshop
Android Development Workshop
Peter Robinett
 
Workshop on How to crack interview
Workshop on How to crack interviewWorkshop on How to crack interview
Workshop on How to crack interview
Adarsh Patel
 
Lecture 08 Xamarin
Lecture 08 XamarinLecture 08 Xamarin
Lecture 08 Xamarin
Maksym Davydov
 

Viewers also liked (20)

Project Analysis - How to Start Project Develoment
Project Analysis - How to Start Project DevelomentProject Analysis - How to Start Project Develoment
Project Analysis - How to Start Project Develoment
 
Workhsop on Logic Building for Programming
Workhsop on Logic Building for ProgrammingWorkhsop on Logic Building for Programming
Workhsop on Logic Building for Programming
 
Workshop on Search Engine Optimization
Workshop on Search Engine OptimizationWorkshop on Search Engine Optimization
Workshop on Search Engine Optimization
 
App indexing api
App indexing apiApp indexing api
App indexing api
 
Hack'n Break Android Workshop
Hack'n Break Android WorkshopHack'n Break Android Workshop
Hack'n Break Android Workshop
 
Lecture 04. Mobile App Design
Lecture 04. Mobile App DesignLecture 04. Mobile App Design
Lecture 04. Mobile App Design
 
Android development session 3 - layout
Android development   session 3 - layoutAndroid development   session 3 - layout
Android development session 3 - layout
 
What's new in Android at I/O'16
What's new in Android at I/O'16What's new in Android at I/O'16
What's new in Android at I/O'16
 
Overview of DroidCon UK 2015
Overview of DroidCon UK 2015 Overview of DroidCon UK 2015
Overview of DroidCon UK 2015
 
Android Udacity Study group 1
Android Udacity Study group 1Android Udacity Study group 1
Android Udacity Study group 1
 
Android development session 4 - Fragments
Android development   session 4 - FragmentsAndroid development   session 4 - Fragments
Android development session 4 - Fragments
 
Fundamental of android
Fundamental of androidFundamental of android
Fundamental of android
 
Working better together designers &amp; developers
Working better together   designers &amp; developersWorking better together   designers &amp; developers
Working better together designers &amp; developers
 
Workshop Android for Java Developers
Workshop Android for Java DevelopersWorkshop Android for Java Developers
Workshop Android for Java Developers
 
Session #8 adding magic to your app
Session #8  adding magic to your appSession #8  adding magic to your app
Session #8 adding magic to your app
 
Management Innovation
Management Innovation Management Innovation
Management Innovation
 
Lecture 06. iOS Programming. Основи Objective-C
Lecture 06. iOS Programming. Основи Objective-CLecture 06. iOS Programming. Основи Objective-C
Lecture 06. iOS Programming. Основи Objective-C
 
Android Development Workshop
Android Development WorkshopAndroid Development Workshop
Android Development Workshop
 
Workshop on How to crack interview
Workshop on How to crack interviewWorkshop on How to crack interview
Workshop on How to crack interview
 
Lecture 08 Xamarin
Lecture 08 XamarinLecture 08 Xamarin
Lecture 08 Xamarin
 

Similar to Optimizing apps for better performance extended

Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"
Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"
Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"
Fwdays
 
Benchmarking PyCon AU 2011 v0
Benchmarking PyCon AU 2011 v0Benchmarking PyCon AU 2011 v0
Benchmarking PyCon AU 2011 v0
Tennessee Leeuwenburg
 
CIS 512 discussion post responses.CPUs and Programming Pleas.docx
CIS 512 discussion post responses.CPUs and Programming Pleas.docxCIS 512 discussion post responses.CPUs and Programming Pleas.docx
CIS 512 discussion post responses.CPUs and Programming Pleas.docx
mccormicknadine86
 
An Introduction to Prometheus (GrafanaCon 2016)
An Introduction to Prometheus (GrafanaCon 2016)An Introduction to Prometheus (GrafanaCon 2016)
An Introduction to Prometheus (GrafanaCon 2016)
Brian Brazil
 
Dot Net Application Monitoring
Dot Net Application MonitoringDot Net Application Monitoring
Dot Net Application Monitoring
Ravi Okade
 
Your data is in Prometheus, now what? (CurrencyFair Engineering Meetup, 2016)
Your data is in Prometheus, now what? (CurrencyFair Engineering Meetup, 2016)Your data is in Prometheus, now what? (CurrencyFair Engineering Meetup, 2016)
Your data is in Prometheus, now what? (CurrencyFair Engineering Meetup, 2016)
Brian Brazil
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
kaven yan
 
The value of reactive
The value of reactiveThe value of reactive
The value of reactive
Stéphane Maldini
 
The Value of Reactive
The Value of ReactiveThe Value of Reactive
The Value of Reactive
VMware Tanzu
 
OORPT Dynamic Analysis
OORPT Dynamic AnalysisOORPT Dynamic Analysis
OORPT Dynamic Analysis
lienhard
 
Java Performance & Profiling
Java Performance & ProfilingJava Performance & Profiling
Java Performance & Profiling
Isuru Perera
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentation
Mennan Tekbir
 
Shorten Device Boot Time for Automotive IVI and Navigation Systems
Shorten Device Boot Time for Automotive IVI and Navigation SystemsShorten Device Boot Time for Automotive IVI and Navigation Systems
Shorten Device Boot Time for Automotive IVI and Navigation Systems
National Cheng Kung University
 
Performance eng prakash.sahu
Performance eng prakash.sahuPerformance eng prakash.sahu
Performance eng prakash.sahu
Dr. Prakash Sahu
 
ab-initio-training basics and architecture
ab-initio-training basics and architectureab-initio-training basics and architecture
ab-initio-training basics and architecture
saipriyacoool
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp North
Philip Norton
 
So You Just Inherited a $Legacy Application… NomadPHP July 2016
So You Just Inherited a $Legacy Application… NomadPHP July 2016So You Just Inherited a $Legacy Application… NomadPHP July 2016
So You Just Inherited a $Legacy Application… NomadPHP July 2016
Joe Ferguson
 
WebSphere Technical University: Introduction to the Java Diagnostic Tools
WebSphere Technical University: Introduction to the Java Diagnostic ToolsWebSphere Technical University: Introduction to the Java Diagnostic Tools
WebSphere Technical University: Introduction to the Java Diagnostic Tools
Chris Bailey
 
Successfully Implement Responsive Design Behavior with Adobe Experience Manager
Successfully Implement Responsive Design Behavior with Adobe Experience ManagerSuccessfully Implement Responsive Design Behavior with Adobe Experience Manager
Successfully Implement Responsive Design Behavior with Adobe Experience Manager
Perficient, Inc.
 
Pref Presentation (2)
Pref Presentation (2)Pref Presentation (2)
Pref Presentation (2)
Prachi Patil
 

Similar to Optimizing apps for better performance extended (20)

Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"
Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"
Александр Махомет "Beyond the code или как мониторить ваш PHP сайт"
 
Benchmarking PyCon AU 2011 v0
Benchmarking PyCon AU 2011 v0Benchmarking PyCon AU 2011 v0
Benchmarking PyCon AU 2011 v0
 
CIS 512 discussion post responses.CPUs and Programming Pleas.docx
CIS 512 discussion post responses.CPUs and Programming Pleas.docxCIS 512 discussion post responses.CPUs and Programming Pleas.docx
CIS 512 discussion post responses.CPUs and Programming Pleas.docx
 
An Introduction to Prometheus (GrafanaCon 2016)
An Introduction to Prometheus (GrafanaCon 2016)An Introduction to Prometheus (GrafanaCon 2016)
An Introduction to Prometheus (GrafanaCon 2016)
 
Dot Net Application Monitoring
Dot Net Application MonitoringDot Net Application Monitoring
Dot Net Application Monitoring
 
Your data is in Prometheus, now what? (CurrencyFair Engineering Meetup, 2016)
Your data is in Prometheus, now what? (CurrencyFair Engineering Meetup, 2016)Your data is in Prometheus, now what? (CurrencyFair Engineering Meetup, 2016)
Your data is in Prometheus, now what? (CurrencyFair Engineering Meetup, 2016)
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
 
The value of reactive
The value of reactiveThe value of reactive
The value of reactive
 
The Value of Reactive
The Value of ReactiveThe Value of Reactive
The Value of Reactive
 
OORPT Dynamic Analysis
OORPT Dynamic AnalysisOORPT Dynamic Analysis
OORPT Dynamic Analysis
 
Java Performance & Profiling
Java Performance & ProfilingJava Performance & Profiling
Java Performance & Profiling
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentation
 
Shorten Device Boot Time for Automotive IVI and Navigation Systems
Shorten Device Boot Time for Automotive IVI and Navigation SystemsShorten Device Boot Time for Automotive IVI and Navigation Systems
Shorten Device Boot Time for Automotive IVI and Navigation Systems
 
Performance eng prakash.sahu
Performance eng prakash.sahuPerformance eng prakash.sahu
Performance eng prakash.sahu
 
ab-initio-training basics and architecture
ab-initio-training basics and architectureab-initio-training basics and architecture
ab-initio-training basics and architecture
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp North
 
So You Just Inherited a $Legacy Application… NomadPHP July 2016
So You Just Inherited a $Legacy Application… NomadPHP July 2016So You Just Inherited a $Legacy Application… NomadPHP July 2016
So You Just Inherited a $Legacy Application… NomadPHP July 2016
 
WebSphere Technical University: Introduction to the Java Diagnostic Tools
WebSphere Technical University: Introduction to the Java Diagnostic ToolsWebSphere Technical University: Introduction to the Java Diagnostic Tools
WebSphere Technical University: Introduction to the Java Diagnostic Tools
 
Successfully Implement Responsive Design Behavior with Adobe Experience Manager
Successfully Implement Responsive Design Behavior with Adobe Experience ManagerSuccessfully Implement Responsive Design Behavior with Adobe Experience Manager
Successfully Implement Responsive Design Behavior with Adobe Experience Manager
 
Pref Presentation (2)
Pref Presentation (2)Pref Presentation (2)
Pref Presentation (2)
 

Optimizing apps for better performance extended

  • 1. Optimizing Apps for Better Performance Elif Boncuk Software Specialist @ Garanti Teknoloji
  • 2. Who am I? ➢Hacettepe - Computer Engineering (2006 - 2011) ➢Garanti Technology - Mobile Applications Team (2011- ) ➢MBA Student @BAU (2014 - ) ➢GDG Istanbul ➢WTM Istanbul ➢Blogger (2010 - ) ➢Photographer @elifbon_ www.elifboncuk.wordpress.com elifboncuk88@gmail.com
  • 9. Overdraw ➢Overdraw is a term used to describe how many times a pixel on the screen has been redrawn in a single frame.
  • 10. Overdraw... 1. On your mobile device, go to Settings and tap Developer Options. 2. In the Hardware accelerated rendering section, select Debug GPU Overdraw. 3. In the Debug GPU overdraw popup, select Show overdraw areas. 4. Don't panic as your screen turns into a delirium of colors. The coloring is provided to help you diagnose your app's display behavior.
  • 11. Overdraw… 5. The colors are hinting at the amount of overdraw on your screen for each pixel, as follows: True color: No overdraw Blue: Overdrawn once Green: Overdrawn twice Pink: Overdrawn three times Red: Overdrawn four or more times
  • 12. Overdraw… How? ➢Eliminate unneeded backgrounds and drawables ➢Define areas will hide portions of view ➢Use RelativeLayout instead of LinearLayout Best Practices: ➢getWindow().setBackgroundDrawable(null ➢android:background:”@null”
  • 13. Clipping ➢Clipping is an optimisation which can be defined as Android framework knows overdraw is a problem and will go out of its way to avoid drawing UI widgets that may be invisible in the final image. ➢Canvas.quickReject() ➢Canvas.clipRect() DRAWABLE ZONE Canvas.clipRect() 20dp 20dp 20dp 20dp
  • 15. Clipping Q: Bu seviyede overdraw yaşanmasına ne sebep olmuş olabilir? 1- Dikkatsiz kod yazarak, çok fazla sayıda background tanımlamış olabiliriz. 2- Kartları ekrana bazı parçaları hidden, birbirinin üstünü örtecek şekilde çizmiş olabiliriz. 3- Bu senaryoda Custom View kullanmamalıydık.
  • 19. Hierarchy Viewer ANDROID_HVPROTO ○ http://developer.android.com/tools/performance/hierarchy-viewer/setup.html ViewServer ○ https://github.com/romainguy/ViewServer Register when created Unregister when destroyed
  • 21. Hierarchy Viewer Bird's-eye view Tree Overview Tree View View Properties Nodes
  • 22. Hierarchy Viewer Each view in your subtree gets three dots, which can be green, yellow, or red. The left dot represents the Draw Process of the rendering pipeline. The middle dot represents the Layout Phase. The right dot represents the Execute Phase.
  • 23. Hierarchy Viewer The color of the dots indicates the relative performance of this node in respect to all other profiled nodes. Green means the view renders faster than at least half of the other views. Yellow means the view renders faster than the bottom half of the other views. Red means the view is among the slowest half of views.
  • 25. Hierarchy Viewer <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com /apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center"> <ImageView android:id="@+id/photo" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <RelativeLayout android:layout_width="100dp" android:layout_height="wrap_content" android:paddingLeft="16dp"> <ImageView android:id="@+id/colorImage" android:layout_width="80dp" android:layout_height="30dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:background="@android:color/holo_green_dark" /> <TextView android:id="@+id/year" android:layout_width="80dp" android:layout_height="30dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:gravity="center"/> <TextView android:id="@+id/day" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/year" android:layout_centerHorizontal="true" /> </RelativeLayout> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:paddingLeft="16dp"> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/place" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
  • 26. Hierarchy Viewer <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <ImageView android:id="@+id/photo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_gravity="center" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/photo" android:paddingLeft="16dp" /> <TextView android:id="@+id/place" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/photo" android:layout_below="@id/name" android:paddingLeft="16dp" /> <TextView android:id="@+id/year" android:layout_width="80dp" android:layout_height="30dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginLeft="16dp" android:background="@android:color/holo_green_dark" android:gravity="center" /> <TextView android:id="@+id/day" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/year" android:layout_alignParentRight="true" android:layout_below="@+id/year" android:layout_marginLeft="16dp" /> </RelativeLayout>
  • 30. Rendering - Tips & Tricks ● getWindow().setBackgroundDrawable(null); // Temadan aldığı renkle aynıysa bu gereksiz ● android:background:”@null” // xml ● Canvas.clipRect(); ● Canvas.quickReject(); ● Flat hiyerarchy ● Gereksiz layoutlardan kaçının ● Use RelativeLayout instead of LinearLayout
  • 32. Profiling with Traceview ➢Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance.
  • 34. Profiling with Traceview The Timeline pane visualizes how your code executes over time. Each row shows a thread. Each bar on the timeline is a method executing. Each color is for a different method; every time a method executes, you see a the same color bar. The width of its bar indicates how long the method takes to execute. The Profiling pane shows a list of methods. Select a method to see who called it (Parent) and who it's calling (Children). The selected method is also highlighted in theTimeline pane. The columns show exclusive and inclusive CPU and real times, percentages, ratios, and how often a method was called. The exclusive time is the time spent just in the method itself, which can help you find issues within that specific method. The inclusive time is for the method and all methods it calls, which can help you find problems with your call tree. The Calls+Rec column shows how many times a method was called recursively, which can help you track down performance issues.
  • 36. Caching for Networking Caching HTTP Responses is disabled by Default. https://www.youtube.com/watch?v=7lxVqqWwTb0&list=PLOU2XLYxmsIKEOXh5TwZEv89aofHzNCiu&index=1
  • 37. Caching for Networking @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... try{ File httpCacheDir = new File(getBaseContext().getCacheDir(),"http"); long httpCacheSize = 10*1024*1024; //10Mib HttpResponseCache.install(httpCacheDir, httpCacheSize); }catch (IOException e){ Log.i(TAG, "HTTP response cache installation failed." + e.getMessage()); } } @Override protected void onStop() { super.onStop(); ... HttpResponseCache cache = HttpResponseCache.getInstalled(); if(null != cache){ cache.flush(); } }
  • 39. Caching for Networking Force a Network Response: Force a Cache Response: http://developer.android.com/reference/android/net/http/HttpResponseCache.html
  • 42. Blocking the UI Thread
  • 43. How to Solve? Android's single thread model: 1. Do not block the UI thread 2. Do not access the Android UI toolkit from outside the UI thread
  • 44. How to Solve? public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png") ; mImageView.post(new Runnable() { public void run() { mImageView.setImageBitmap(bitmap); } }); } }).start(); } public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = loadImageFromNetwork("http://example.com/image.p ng"); mImageView.setImageBitmap(b); } }).start(); }
  • 45. How to Solve? public void onClick(View v) { new DownloadImageTask().execute("http://example.com/image.png"); } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { /** The system calls this to perform work in a worker thread and * delivers it the parameters given to AsyncTask.execute() */ protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); } }
  • 46. Analyzing UI Performance with Systrace ➢The Systrace tool allows you to collect and inspect timing information across an entire Android device, which is called a trace. ➢As simply, you should put your code that you want to trace between this two lines. Trace.beginSection("Data Structures"); // TODO: Trace.endSection();
  • 47. Analyzing UI Performance with Systrace Bad Performance Example
  • 48. Analyzing UI Performance with Systrace
  • 49. Analyzing UI Performance with Systrace
  • 50. Memory Basic Prinsiples of Garbage Collection: ➢Find data objects in a program that cannot be accesed in the future. ➢Reclaim the resources used by those objects.
  • 51. Memory Monitor Memory Monitor reports in real-time how your app allocates memory. ➢Showing available and used memory in a graph, and garbage collection events over time. ➢Quickly testing whether app slowness might be related to excessive garbage collection events. ➢Quickly testing whether app crashes may be related to running out of memory. Dark blue: Amount of memory that your app is currently using. Light blue: Available, unallocated memory.
  • 52.
  • 54. Heap Viewer Heap Viewer reports in real-time what types of objects your application has allocated, how many, and their sizes on the heap. ➢Getting a sense of how your app allocates and frees memory. ➢Identifying memory leaks. ➢5.0+
  • 56. Allocation Tracker Allocation Tracker records an app's memory allocations and lists all allocated objects for the profiling cycle with their call stack, size, and allocating code. ➢Identifying where many similar object types, from roughly the same call stack, are allocated and deallocated over a very short period of time. ➢Finding the places in your code that may contribute to inefficient memory use.
  • 57. How your app should manage memory ➢ Use services sparingly ➢ Release memory when your user interface becomes hidden ➢ Release memory as memory becomes tight ➢ Check how much memory you should use ➢ Avoid wasting memory with bitmaps ➢ Use optimized data containers ➢ Be aware of memory overhead ➢ Be careful with code abstractions ➢ Use nano protobufs for serialized data ➢ Avoid dependency injection frameworks ➢ Be careful about using external libraries ➢ Optimize overall performance ➢ Use ProGuard to strip out any unneeded code http://developer.android.com/training/articles/memory.html
  • 59. Batterystats & Battery Historian Batterystats collects battery data from your device, and Battery Historian converts that data into an HTML visualization that you can view in your Browser. ➢Showing you where and how processes are drawing current from the battery. ➢Identifying tasks in your app that could be deferred or even removed to improve battery life. ➢5.0+
  • 61. Batterystats & Battery Historian battery_level: When the battery level was recorded and logged. top: The application running at the top. wifi_running: Shows that the Wi-Fi network connection was active. screen: Screen is turned on. phone_in_call: Recorded when the phone is in a call. wake_lock: App wakes up, grabs a lock, does small work, then goes back to sleep. Trunning: Shows when the CPU is awake. Check whether it is awake and asleep when you expect it to be. wake_reason: The last thing that caused the kernel to wake up. If it's your app, determine whether it was necessary. mobile_radio: Shows when the radio was on. Starting the radio is battery expensive. Many narrow bars close to each other can indicate opportunities for batching and other optimizations. gps: Indicates when the GPS was on. Make sure this is what you expect.
  • 62. Batterystats & Battery Historian Battery History: A time series of power-relevant events, such as screen, Wi-Fi, and app launch. These are also visible through Battery Historian. Per-PID Stats: How long each process ran. Statistics since last charge: System-wide statistics, such as cell signal levels and screen brightness. Provides an overall picture of what's happening with the device. This information is especially useful to make sure no external events are affecting your experiment. Estimated power use (mAh) by UID and peripheral: This is currently an extremely rough estimate and should not be considered experiment data. Per-app mobile ms per packet: Radio-awake-time divided by packets sent. An efficient app will transfer all its traffic in batches, so the lower this number the better. All partial wake locks: All app-held wakelocks, by aggregate duration and count.
  • 66. Adapting to Latency ConnectivityManager cm = (ConnectivityManager)getBaseContext().getSystemService(Context.CONNE CTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if(activeNetwork.getType() != ConnectivityManager.TYPE_WIFI){ String typeName = activeNetwork.getSubtypeName(); int type = activeNetwork.getSubtype(); switch (type){ // TelephonyManager.NETWORK_TYPE *enums } }
  • 68. Adapting to Latency ● Emulator Throttling ● Network Attenuator
  • 70. Wakelock API private void pollServer() { mWakeLockMsg.setText("Polling the server! This day sure went by fast."); for (int i=0; i<10; i++) { mWakeLock.acquire(); mWakeLockMsg.append("Connection attempt, take " + i + ":n"); mWakeLockMsg.append(getString(R.string.wakelock_acquired)); // Always check that the network is available before trying to connect. You don't want // to break things and embarrass yourself. if (isNetworkConnected()) { new SimpleDownloadTask().execute(); } else { mWakeLockMsg.append("No connection on job " + i + "; SAD FACE"); } } } @Override protected void onPostExecute(String result) { mWakeLockMsg.append("n" + result + "n"); releaseWakeLock(); }
  • 71. JobScheduler mServiceComponent = new ComponentName(this, MyJobService.class); @Override public boolean onStartJob(JobParameters params) { Log.i(LOG_TAG, "Totally and completely working on job " + params.getJobId()); // First, check the network, and then attempt to connect. if (isNetworkConnected()) { new SimpleDownloadTask() .execute(params); return true; } else { Log.i(LOG_TAG, "No connection on job " + params.getJobId() + "; sad face"); } return false; } public void pollServer() { JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); for (int i=0; i<10; i++) { JobInfo jobInfo = new JobInfo.Builder(i, mServiceComponent) .setMinimumLatency(5000) // 5 seconds .setOverrideDeadline(60000) // 60 seconds (for brevity in the sample) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) // WiFi or data connections .build(); mWakeLockMsg.append("Scheduling job " + i + "!n"); scheduler.schedule(jobInfo); } }
  • 74. Lint
  • 75. Lint