SlideShare a Scribd company logo
1 of 83
A good memory is one trained to forget the trivial
Where is my RAM, dude?
+
First,
Yonatan Levin
Google Developer Expert &
Android @ Gett
Idan Felix
Senior Android & Redhead
Varonis
Jonathan Yarkoni
Android Developer &
Advocate
Ironsource
Android Academy Staff
Britt Barak
Android Lead
Real
Muiriel Felix
Android Design
Logistics
https://www.facebook.com/groups/android.academy.ils/
#PerfMatters
What’s next?
30/5 - Felix
- How to draw right? ( Overdraw, Cliprect, Bitmaps)
13/6 - Britt
- View, Animations
What’s next?
4/7 - Yonatan
- Networking, JSON, Batching, Location
10/8 - Felix
- Battery & CPU
What’s next?
14/9 - Britt
- Threadinggg...
And…
31.10
New course coming
Memory mmm…
OutOfMemory is just an iceberg of problems with a memory
Wow! What should I do?
1.Be Aware
2.Learn & Understand
3.Apply - Profile your code
I’m
Collector,
Garbage Collector
GC
Goal
1.Find objects that can’t be accessed
2.Reclaim the resource from them
Mark & Sweeping
So what happens when we don’t have enough
free space for our “new Object();”?
Larger heap
Pitfall
More Garbage = Larger GC Pauses
Dalvik
07-01 15:56:16.785: I/dalvikvm-heap(30615): Grow heap (frag case) to 38.179MB for
8294416-byte allocation
07-01 15:56:17.625: I/Choreographer(30615): Skipped 35 frames! The application may be
doing too much work on its main thread.
07-01 15:56:19.035: D/dalvikvm(30615): GC_CONCURRENT freed 35838K, 43% free
51351K/89052K, paused 3ms+5ms, total 106ms
07-01 15:56:19.035: D/dalvikvm(30615): WAIT_FOR_CONCURRENT_GC blocked 96ms
GC Reason
GC_CONCURRENT - A concurrent GC that frees up memory as your heap begins to fill up.
GC_FOR_MALLOC - A GC caused because your app attempted to allocate memory when your
heap was already full, so the system had to stop your app and reclaim memory.
GC_HPROF_DUMP_HEAP - A GC that occurs when you request to create an HPROF file to
analyze your heap.
GC_EXPLICIT - An explicit GC, such as when you call gc() (which you should avoid
calling and instead trust the GC to run when needed).
GC_EXTERNAL_ALLOC - This happens only on API level 10 and lower (newer versions
allocate everything in the Dalvik heap). A GC for externally allocated memory (such
as the pixel data stored in native memory or NIO byte buffers).
ART
07-01 16:00:44.531: I/art(198): Explicit concurrent mark sweep GC freed 700(30KB)
AllocSpace objects, 0(0B) LOS objects, 792% free, 18MB/21MB, paused 186us total
12.763ms
07-01 16:00:46.517: I/art(29197): Background partial concurrent mark sweep GC freed
74626(3MB) AllocSpace objects, 39(4MB) LOS objects, 1496% free, 25MB/32MB, paused
4.422ms total 1.371747s
07-01 16:00:48.534: I/Choreographer(29197): Skipped 30 frames! The application may be
doing too much work on its main thread.
07-01 16:00:48.566: I/art(29197): Background sticky concurrent mark sweep GC freed
70319(3MB) AllocSpace objects, 59(5MB) LOS objects, 825% free, 49MB/56MB, paused
6.139ms total 52.868ms
GC Reason
Concurrent - A concurrent GC which does not suspend app threads. This GC runs in a
background thread and does not prevent allocations.
Alloc - The GC was initiated because your app attempted to allocate memory when your
heap was already full. In this case, the garbage collection occurred in the
allocating thread.
Explicit - The garbage collection was explicitly requested by an app, for instance,
by calling gc() or gc().
NativeAlloc - The collection was caused by native memory pressure from native
allocations such as Bitmaps or RenderScript allocation objects
Why i care about memory
60FPS!!!
But How Does It Work?
But How Does It Work?
Smooth
Motion
60
No
Difference
60+
Flip Book
12
Movies
Frames Per Second
Fluid Motion
24
+effects
We Have A Winner!
Smooth
Motion
60
No
Difference
60+
Flip Book
12
Movies
Frames Per Second
Fluid Motion
24
+effects
Smooth
Motion
60
60 FPS
60 Frames / Second =
Frame / 16.666 Millisecond
Okey, Okey
I got the idea.
What’s next?
Reasons
1.A lot of allocations
2.Memory leaks
3.Not designing for performance
Memory churn
public void startAllocations(View view) {
AndroidAcademy object;
for (int i = 0; i < 1000; i++) {
object = new AndroidAcademy();
}
}
A Volume hit the GC
When usually avoid it happen
1.onDraw()
2.String concatenation on buffer reading from stream
3.Inner loops allocation
Good Practice
1.Allocate outside of the loop
2.Consider reuse of the object
3.Pool of objects
4.To think does it really necessary?
Memory Leak
public class MainActivity extends AppCompatActivity {
private static Drawable sBackground;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.text);
textView.setText("Leak fun!");
if (sBackground == null) {
sBackground = ContextCompat.getDrawable(this,android.R.drawable.ic_menu_zoom);
}
textView.setBackgroundDrawable(sBackground);
}
Detecting Memory Issues
GC now!
Dump Java
Heap
Start
Allocation
Tracker
LeakCanary
How to?
public class GetTaxiDriverBoxApp extends Application {
protected RefWatcher mRefWatcher;
public void onCreate() {
super.onCreate();
mRefWatcher = installLeakCanary();
}
protected RefWatcher installLeakCanary() {
return RefWatcher.DISABLED;
}
}
In Debug Only
public class DebugApplication extends GetTaxiDriverBoxApp {
@Override
protected RefWatcher installLeakCanary() {
mRefWatcher = LeakCanary.install(this, LeakSlackUploadService.class,
AndroidExcludedRefs.createAppDefaults().build());
return mRefWatcher;
}
}
When should be killed - watched it
@Override
public void onDetach() {
super.onDetach();
GetTaxiDriverBoxApp.getRefWatcher(getContext()).watch(this);
}
Let’s dive into some examples
Memory Leak Life Example Google Maps
* GC ROOT thread java.lang.Thread.<Java Local> (named 'AsyncTask #5')
* references android.os.AsyncTask$3.this$0 (anonymous class extends
java.util.concurrent.FutureTask)
* references com.google.maps.android.clustering.ClusterManager$ClusterTask.this$0
* references com.google.maps.android.clustering.ClusterManager.mRenderer
* references
com.gettaxi.dbx_lib.features.heatmap.FixedBucketsResizingDrawableClusterRenderer.mIconGenerator
* references com.google.maps.android.ui.IconGenerator.mContext
* leaks com.gettaxi.dbx.android.activities.MainActivity instance
Memory Leak Life Example
Some of them are really hard to spot
Memory Leak - Example
* GC ROOT thread com.squareup.picasso.Dispatcher.DispatcherThread.<Java Local>
* references android.os.Message.obj
* references com.example.MyActivity$MyDialogClickListener.this$0
* leaks com.example.MyActivity.MainActivity instance
Handler.java
public final Message obtainMessage(int what, Object obj) {
return Message.obtain(this, what, obj);
}
public void handleMessage(Message msg) {
switch (msg.what) {
case WHAT_ORDER_UPDATES: {
//do something
break;
}
}
Simple Dialog
new AlertDialog.Builder(this)
.setPositiveButton("Baguette", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
MyActivity.this.makeBread();
}
}).show();
.class of OnClickListener
class MyActivity$0 implements DialogInterface.OnClickListener {
final MyActivity this$0;
MyActivity$0(MyActivity this$0) {
this.this$0 = this$0;
}
@Override public void onClick(DialogInterface dialog, int which) {
this$0.makeBread();
}
}
new AlertDialog.Builder(this)
.setPositiveButton("Baguette", new MyActivity$0(this));
.show();
AlertController.java
public void setButton(int whichButton, CharSequence text,
DialogInterface.OnClickListener listener, Message msg) {
if (msg == null && listener != null) {
msg = mHandler.obtainMessage(whichButton, listener);
}
switch (whichButton) {
case DialogInterface.BUTTON_POSITIVE:
mButtonPositiveText = text;
mButtonPositiveMessage = msg;
break;
//...
private final View.OnClickListener mButtonHandler = new View.OnClickListener() {
@Override public void onClick(View v) {
final Message m;
if (v == mButtonPositive && mButtonPositiveMessage != null) {
m = Message.obtain(mButtonPositiveMessage);
}
//...some other code
if (m != null) {
m.sendToTarget();
}
// Post a message so we dismiss after the above handlers are executed.
mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface)
.sendToTarget();
}
Fix?
Check the square blog
Wrapper for clickListener and clear it on detach
Or
Send idle messages to clean app the messages
https://corner.squareup.com/2015/08/a-small-leak.html
Good Practices
Do not keep long-lived references to a context-
activity
public static Context mContext;
public NoLifeCycleClass(Activity myActivity) {
mContext = (Context) myActivity;
}
Try using the context-application instead of a
context-activity
StringUtilsUI.doSomeLongRunningTask(getApplicationContext());
Avoid non-static inner classes
public class DialogCountdown extends BaseDialogFragment {
private class CountDownHandler extends Handler {
//do some work
}
}
Avoid non-static inner classes
private static class CountDownHandler extends Handler {
private final WeakReference<DialogCountdown> mDialogCountdownWeakReference;
public CountDownHandler(DialogCountdown dialogCountdown) {
super();
mDialogCountdownWeakReference = new WeakReference<>(dialogCountdown);
}
public void handleMessage(Message msg) {
if(mDialogCountdownWeakReference.get()!=null) {
mDialogCountdownWeakReference.get().onCountDown();
}
}
Clean/Stop all your handlers, animation listeners
onDestroy();
protected void onStop() {
super.onStop();
mHandler.clearAllMessages();
unregisterReceivers();
heatMapsDone();
if (mServiceBound) {
mServiceBound = false;
Services.unbindFromRidesService(this, this);
}
if (mMapStateMachine != null) {
mMapStateMachine.stop();
mMapStateMachine = null;
}
}
Last world...
Today
With Proguard
Jack
Jill
http://trickyandroid.com/the-dark-world-of-jack-and-jill/
Performance #1   memory

More Related Content

What's hot

Home Automation with Android Things and the Google Assistant
Home Automation with Android Things and the Google AssistantHome Automation with Android Things and the Google Assistant
Home Automation with Android Things and the Google AssistantNilhcem
 
HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?Ankara JUG
 
The Ring programming language version 1.2 book - Part 35 of 84
The Ring programming language version 1.2 book - Part 35 of 84The Ring programming language version 1.2 book - Part 35 of 84
The Ring programming language version 1.2 book - Part 35 of 84Mahmoud Samir Fayed
 
The quantum computers are coming - VoxxedDays Bristol 2018
The quantum computers are coming - VoxxedDays Bristol 2018The quantum computers are coming - VoxxedDays Bristol 2018
The quantum computers are coming - VoxxedDays Bristol 2018Alasdair Collinson
 
Performance #6 threading
Performance #6  threadingPerformance #6  threading
Performance #6 threadingVitali Pekelis
 
HoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingHoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingTakashi Yoshinaga
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
The quantum computers are coming - VoxxedDays Cluj-Napoca 2018
The quantum computers are coming - VoxxedDays Cluj-Napoca 2018The quantum computers are coming - VoxxedDays Cluj-Napoca 2018
The quantum computers are coming - VoxxedDays Cluj-Napoca 2018Alasdair Collinson
 
Introducing AlloyUI DiagramBuilder
Introducing AlloyUI DiagramBuilderIntroducing AlloyUI DiagramBuilder
Introducing AlloyUI DiagramBuilderEduardo Lundgren
 
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012Eduardo Lundgren
 

What's hot (13)

Mattbrenner
MattbrennerMattbrenner
Mattbrenner
 
Home Automation with Android Things and the Google Assistant
Home Automation with Android Things and the Google AssistantHome Automation with Android Things and the Google Assistant
Home Automation with Android Things and the Google Assistant
 
HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?
 
The Ring programming language version 1.2 book - Part 35 of 84
The Ring programming language version 1.2 book - Part 35 of 84The Ring programming language version 1.2 book - Part 35 of 84
The Ring programming language version 1.2 book - Part 35 of 84
 
The quantum computers are coming - VoxxedDays Bristol 2018
The quantum computers are coming - VoxxedDays Bristol 2018The quantum computers are coming - VoxxedDays Bristol 2018
The quantum computers are coming - VoxxedDays Bristol 2018
 
Performance #6 threading
Performance #6  threadingPerformance #6  threading
Performance #6 threading
 
HoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingHoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial Mapping
 
Sequence diagrams
Sequence diagramsSequence diagrams
Sequence diagrams
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
The quantum computers are coming - VoxxedDays Cluj-Napoca 2018
The quantum computers are coming - VoxxedDays Cluj-Napoca 2018The quantum computers are coming - VoxxedDays Cluj-Napoca 2018
The quantum computers are coming - VoxxedDays Cluj-Napoca 2018
 
Introducing AlloyUI DiagramBuilder
Introducing AlloyUI DiagramBuilderIntroducing AlloyUI DiagramBuilder
Introducing AlloyUI DiagramBuilder
 
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
 
Lambda expressions in C++
Lambda expressions in C++Lambda expressions in C++
Lambda expressions in C++
 

Viewers also liked

Session #6 loaders and adapters
Session #6  loaders and adaptersSession #6  loaders and adapters
Session #6 loaders and adaptersVitali Pekelis
 
Android pro tips trilogy
Android  pro tips trilogyAndroid  pro tips trilogy
Android pro tips trilogyVitali Pekelis
 
Lecture #3 activities and intents
Lecture #3  activities and intentsLecture #3  activities and intents
Lecture #3 activities and intentsVitali Pekelis
 
Session #7 rich and responsive layouts
Session #7  rich and responsive layoutsSession #7  rich and responsive layouts
Session #7 rich and responsive layoutsVitali Pekelis
 
Lecture #1 Creating your first android project
Lecture #1  Creating your first android projectLecture #1  Creating your first android project
Lecture #1 Creating your first android projectVitali Pekelis
 
Session #5 content providers
Session #5  content providersSession #5  content providers
Session #5 content providersVitali Pekelis
 
Android material design lecture #2
Android material design   lecture #2Android material design   lecture #2
Android material design lecture #2Vitali Pekelis
 
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 appVitali Pekelis
 
Android design lecture #1
Android design   lecture #1Android design   lecture #1
Android design lecture #1Vitali Pekelis
 

Viewers also liked (9)

Session #6 loaders and adapters
Session #6  loaders and adaptersSession #6  loaders and adapters
Session #6 loaders and adapters
 
Android pro tips trilogy
Android  pro tips trilogyAndroid  pro tips trilogy
Android pro tips trilogy
 
Lecture #3 activities and intents
Lecture #3  activities and intentsLecture #3  activities and intents
Lecture #3 activities and intents
 
Session #7 rich and responsive layouts
Session #7  rich and responsive layoutsSession #7  rich and responsive layouts
Session #7 rich and responsive layouts
 
Lecture #1 Creating your first android project
Lecture #1  Creating your first android projectLecture #1  Creating your first android project
Lecture #1 Creating your first android project
 
Session #5 content providers
Session #5  content providersSession #5  content providers
Session #5 content providers
 
Android material design lecture #2
Android material design   lecture #2Android material design   lecture #2
Android material design lecture #2
 
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
 
Android design lecture #1
Android design   lecture #1Android design   lecture #1
Android design lecture #1
 

Similar to Performance #1 memory

dotMemory 4 - What's inside?
dotMemory 4 - What's inside?dotMemory 4 - What's inside?
dotMemory 4 - What's inside?Maarten Balliauw
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaXamarin
 
Common mistakes in android development
Common mistakes in android developmentCommon mistakes in android development
Common mistakes in android developmentHoang Nguyen Huu
 
Back To The Future.Key 2
Back To The Future.Key 2Back To The Future.Key 2
Back To The Future.Key 2gueste8cc560
 
Memory management for_android_apps
Memory management for_android_appsMemory management for_android_apps
Memory management for_android_appsBin Shao
 
Naive application development
Naive application developmentNaive application development
Naive application developmentShaka Huang
 
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"LogeekNightUkraine
 
Interact your wearable and an iot device
Interact your wearable and an iot deviceInteract your wearable and an iot device
Interact your wearable and an iot deviceJeff Prestes
 
He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!François-Guillaume Ribreau
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Peter Higgins
 
PythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummiesPythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummiesTatiana Al-Chueyr
 
Back To The Future
Back To The FutureBack To The Future
Back To The FutureBill Scott
 
Exploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyExploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyMike Hagedorn
 
C++ memory leak detection
C++ memory leak detectionC++ memory leak detection
C++ memory leak detectionVõ Hòa
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
Performance #5 cpu and battery
Performance #5  cpu and batteryPerformance #5  cpu and battery
Performance #5 cpu and batteryVitali Pekelis
 
Connecting your phone and home with firebase and android things - James Cogga...
Connecting your phone and home with firebase and android things - James Cogga...Connecting your phone and home with firebase and android things - James Cogga...
Connecting your phone and home with firebase and android things - James Cogga...DroidConTLV
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?ColdFusionConference
 

Similar to Performance #1 memory (20)

dotMemory 4 - What's inside?
dotMemory 4 - What's inside?dotMemory 4 - What's inside?
dotMemory 4 - What's inside?
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
 
Common mistakes in android development
Common mistakes in android developmentCommon mistakes in android development
Common mistakes in android development
 
Back To The Future.Key 2
Back To The Future.Key 2Back To The Future.Key 2
Back To The Future.Key 2
 
Memory management for_android_apps
Memory management for_android_appsMemory management for_android_apps
Memory management for_android_apps
 
Naive application development
Naive application developmentNaive application development
Naive application development
 
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
 
Interact your wearable and an iot device
Interact your wearable and an iot deviceInteract your wearable and an iot device
Interact your wearable and an iot device
 
He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!
 
Talking trash
Talking trashTalking trash
Talking trash
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
PythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummiesPythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummies
 
Back To The Future
Back To The FutureBack To The Future
Back To The Future
 
Exploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyExploring the Internet of Things Using Ruby
Exploring the Internet of Things Using Ruby
 
C++ memory leak detection
C++ memory leak detectionC++ memory leak detection
C++ memory leak detection
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
Performance #5 cpu and battery
Performance #5  cpu and batteryPerformance #5  cpu and battery
Performance #5 cpu and battery
 
Connecting your phone and home with firebase and android things - James Cogga...
Connecting your phone and home with firebase and android things - James Cogga...Connecting your phone and home with firebase and android things - James Cogga...
Connecting your phone and home with firebase and android things - James Cogga...
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 

More from Vitali Pekelis

Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Vitali Pekelis
 
Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Vitali Pekelis
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architectureVitali Pekelis
 
Advanced #4 GPU & Animations
Advanced #4   GPU & AnimationsAdvanced #4   GPU & Animations
Advanced #4 GPU & AnimationsVitali Pekelis
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networkingVitali Pekelis
 
Advanced #1 cpu, memory
Advanced #1   cpu, memoryAdvanced #1   cpu, memory
Advanced #1 cpu, memoryVitali Pekelis
 
All the support you need. Support libs in Android
All the support you need. Support libs in AndroidAll the support you need. Support libs in Android
All the support you need. Support libs in AndroidVitali Pekelis
 
How to build Sdk? Best practices
How to build Sdk? Best practicesHow to build Sdk? Best practices
How to build Sdk? Best practicesVitali Pekelis
 
Android design patterns
Android design patternsAndroid design patterns
Android design patternsVitali Pekelis
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading Vitali Pekelis
 
Mobile ui fruit or delicious sweets
Mobile ui  fruit or delicious sweetsMobile ui  fruit or delicious sweets
Mobile ui fruit or delicious sweetsVitali Pekelis
 
Lecture #4 c loaders and co.
Lecture #4 c   loaders and co.Lecture #4 c   loaders and co.
Lecture #4 c loaders and co.Vitali Pekelis
 
Session #4 b content providers
Session #4 b  content providersSession #4 b  content providers
Session #4 b content providersVitali Pekelis
 
Advanced #2 - ui perf
 Advanced #2 - ui perf Advanced #2 - ui perf
Advanced #2 - ui perfVitali Pekelis
 
Android design lecture #3
Android design   lecture #3Android design   lecture #3
Android design lecture #3Vitali Pekelis
 

More from Vitali Pekelis (20)

Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940
 
Droidkaigi 2019
Droidkaigi 2019Droidkaigi 2019
Droidkaigi 2019
 
Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019
 
Android Q 2019
Android Q 2019Android Q 2019
Android Q 2019
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architecture
 
Advanced #4 GPU & Animations
Advanced #4   GPU & AnimationsAdvanced #4   GPU & Animations
Advanced #4 GPU & Animations
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networking
 
Advanced #2 threading
Advanced #2   threadingAdvanced #2   threading
Advanced #2 threading
 
Advanced #1 cpu, memory
Advanced #1   cpu, memoryAdvanced #1   cpu, memory
Advanced #1 cpu, memory
 
All the support you need. Support libs in Android
All the support you need. Support libs in AndroidAll the support you need. Support libs in Android
All the support you need. Support libs in Android
 
How to build Sdk? Best practices
How to build Sdk? Best practicesHow to build Sdk? Best practices
How to build Sdk? Best practices
 
Di &amp; dagger
Di &amp; daggerDi &amp; dagger
Di &amp; dagger
 
Android design patterns
Android design patternsAndroid design patterns
Android design patterns
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading
 
Mobile ui fruit or delicious sweets
Mobile ui  fruit or delicious sweetsMobile ui  fruit or delicious sweets
Mobile ui fruit or delicious sweets
 
Lecture #4 c loaders and co.
Lecture #4 c   loaders and co.Lecture #4 c   loaders and co.
Lecture #4 c loaders and co.
 
Session #4 b content providers
Session #4 b  content providersSession #4 b  content providers
Session #4 b content providers
 
Advanced #2 - ui perf
 Advanced #2 - ui perf Advanced #2 - ui perf
Advanced #2 - ui perf
 
Android meetup
Android meetupAndroid meetup
Android meetup
 
Android design lecture #3
Android design   lecture #3Android design   lecture #3
Android design lecture #3
 

Recently uploaded

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Recently uploaded (20)

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 

Performance #1 memory

  • 1. A good memory is one trained to forget the trivial Where is my RAM, dude? +
  • 3. Yonatan Levin Google Developer Expert & Android @ Gett Idan Felix Senior Android & Redhead Varonis Jonathan Yarkoni Android Developer & Advocate Ironsource Android Academy Staff Britt Barak Android Lead Real Muiriel Felix Android Design
  • 6.
  • 8. What’s next? 30/5 - Felix - How to draw right? ( Overdraw, Cliprect, Bitmaps) 13/6 - Britt - View, Animations
  • 9. What’s next? 4/7 - Yonatan - Networking, JSON, Batching, Location 10/8 - Felix - Battery & CPU
  • 10. What’s next? 14/9 - Britt - Threadinggg... And…
  • 13.
  • 14.
  • 15. OutOfMemory is just an iceberg of problems with a memory
  • 16.
  • 18. 1.Be Aware 2.Learn & Understand 3.Apply - Profile your code
  • 20. GC
  • 21. Goal 1.Find objects that can’t be accessed 2.Reclaim the resource from them
  • 23. So what happens when we don’t have enough free space for our “new Object();”?
  • 25.
  • 27. More Garbage = Larger GC Pauses
  • 28. Dalvik 07-01 15:56:16.785: I/dalvikvm-heap(30615): Grow heap (frag case) to 38.179MB for 8294416-byte allocation 07-01 15:56:17.625: I/Choreographer(30615): Skipped 35 frames! The application may be doing too much work on its main thread. 07-01 15:56:19.035: D/dalvikvm(30615): GC_CONCURRENT freed 35838K, 43% free 51351K/89052K, paused 3ms+5ms, total 106ms 07-01 15:56:19.035: D/dalvikvm(30615): WAIT_FOR_CONCURRENT_GC blocked 96ms
  • 29. GC Reason GC_CONCURRENT - A concurrent GC that frees up memory as your heap begins to fill up. GC_FOR_MALLOC - A GC caused because your app attempted to allocate memory when your heap was already full, so the system had to stop your app and reclaim memory. GC_HPROF_DUMP_HEAP - A GC that occurs when you request to create an HPROF file to analyze your heap. GC_EXPLICIT - An explicit GC, such as when you call gc() (which you should avoid calling and instead trust the GC to run when needed). GC_EXTERNAL_ALLOC - This happens only on API level 10 and lower (newer versions allocate everything in the Dalvik heap). A GC for externally allocated memory (such as the pixel data stored in native memory or NIO byte buffers).
  • 30. ART 07-01 16:00:44.531: I/art(198): Explicit concurrent mark sweep GC freed 700(30KB) AllocSpace objects, 0(0B) LOS objects, 792% free, 18MB/21MB, paused 186us total 12.763ms 07-01 16:00:46.517: I/art(29197): Background partial concurrent mark sweep GC freed 74626(3MB) AllocSpace objects, 39(4MB) LOS objects, 1496% free, 25MB/32MB, paused 4.422ms total 1.371747s 07-01 16:00:48.534: I/Choreographer(29197): Skipped 30 frames! The application may be doing too much work on its main thread. 07-01 16:00:48.566: I/art(29197): Background sticky concurrent mark sweep GC freed 70319(3MB) AllocSpace objects, 59(5MB) LOS objects, 825% free, 49MB/56MB, paused 6.139ms total 52.868ms
  • 31. GC Reason Concurrent - A concurrent GC which does not suspend app threads. This GC runs in a background thread and does not prevent allocations. Alloc - The GC was initiated because your app attempted to allocate memory when your heap was already full. In this case, the garbage collection occurred in the allocating thread. Explicit - The garbage collection was explicitly requested by an app, for instance, by calling gc() or gc(). NativeAlloc - The collection was caused by native memory pressure from native allocations such as Bitmaps or RenderScript allocation objects
  • 32. Why i care about memory
  • 34. But How Does It Work?
  • 35. But How Does It Work? Smooth Motion 60 No Difference 60+ Flip Book 12 Movies Frames Per Second Fluid Motion 24 +effects
  • 36. We Have A Winner! Smooth Motion 60 No Difference 60+ Flip Book 12 Movies Frames Per Second Fluid Motion 24 +effects Smooth Motion 60
  • 37. 60 FPS 60 Frames / Second = Frame / 16.666 Millisecond
  • 38.
  • 39. Okey, Okey I got the idea. What’s next?
  • 40. Reasons 1.A lot of allocations 2.Memory leaks 3.Not designing for performance
  • 41. Memory churn public void startAllocations(View view) { AndroidAcademy object; for (int i = 0; i < 1000; i++) { object = new AndroidAcademy(); } }
  • 42.
  • 43. A Volume hit the GC
  • 44. When usually avoid it happen 1.onDraw() 2.String concatenation on buffer reading from stream 3.Inner loops allocation
  • 45. Good Practice 1.Allocate outside of the loop 2.Consider reuse of the object 3.Pool of objects 4.To think does it really necessary?
  • 46. Memory Leak public class MainActivity extends AppCompatActivity { private static Drawable sBackground; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = (TextView) findViewById(R.id.text); textView.setText("Leak fun!"); if (sBackground == null) { sBackground = ContextCompat.getDrawable(this,android.R.drawable.ic_menu_zoom); } textView.setBackgroundDrawable(sBackground); }
  • 47.
  • 49.
  • 51.
  • 52.
  • 54.
  • 55. How to? public class GetTaxiDriverBoxApp extends Application { protected RefWatcher mRefWatcher; public void onCreate() { super.onCreate(); mRefWatcher = installLeakCanary(); } protected RefWatcher installLeakCanary() { return RefWatcher.DISABLED; } }
  • 56. In Debug Only public class DebugApplication extends GetTaxiDriverBoxApp { @Override protected RefWatcher installLeakCanary() { mRefWatcher = LeakCanary.install(this, LeakSlackUploadService.class, AndroidExcludedRefs.createAppDefaults().build()); return mRefWatcher; } }
  • 57. When should be killed - watched it @Override public void onDetach() { super.onDetach(); GetTaxiDriverBoxApp.getRefWatcher(getContext()).watch(this); }
  • 58. Let’s dive into some examples
  • 59. Memory Leak Life Example Google Maps * GC ROOT thread java.lang.Thread.<Java Local> (named 'AsyncTask #5') * references android.os.AsyncTask$3.this$0 (anonymous class extends java.util.concurrent.FutureTask) * references com.google.maps.android.clustering.ClusterManager$ClusterTask.this$0 * references com.google.maps.android.clustering.ClusterManager.mRenderer * references com.gettaxi.dbx_lib.features.heatmap.FixedBucketsResizingDrawableClusterRenderer.mIconGenerator * references com.google.maps.android.ui.IconGenerator.mContext * leaks com.gettaxi.dbx.android.activities.MainActivity instance
  • 60. Memory Leak Life Example
  • 61. Some of them are really hard to spot
  • 62. Memory Leak - Example * GC ROOT thread com.squareup.picasso.Dispatcher.DispatcherThread.<Java Local> * references android.os.Message.obj * references com.example.MyActivity$MyDialogClickListener.this$0 * leaks com.example.MyActivity.MainActivity instance
  • 63. Handler.java public final Message obtainMessage(int what, Object obj) { return Message.obtain(this, what, obj); } public void handleMessage(Message msg) { switch (msg.what) { case WHAT_ORDER_UPDATES: { //do something break; } }
  • 64. Simple Dialog new AlertDialog.Builder(this) .setPositiveButton("Baguette", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MyActivity.this.makeBread(); } }).show();
  • 65. .class of OnClickListener class MyActivity$0 implements DialogInterface.OnClickListener { final MyActivity this$0; MyActivity$0(MyActivity this$0) { this.this$0 = this$0; } @Override public void onClick(DialogInterface dialog, int which) { this$0.makeBread(); } } new AlertDialog.Builder(this) .setPositiveButton("Baguette", new MyActivity$0(this)); .show();
  • 66. AlertController.java public void setButton(int whichButton, CharSequence text, DialogInterface.OnClickListener listener, Message msg) { if (msg == null && listener != null) { msg = mHandler.obtainMessage(whichButton, listener); } switch (whichButton) { case DialogInterface.BUTTON_POSITIVE: mButtonPositiveText = text; mButtonPositiveMessage = msg; break; //...
  • 67. private final View.OnClickListener mButtonHandler = new View.OnClickListener() { @Override public void onClick(View v) { final Message m; if (v == mButtonPositive && mButtonPositiveMessage != null) { m = Message.obtain(mButtonPositiveMessage); } //...some other code if (m != null) { m.sendToTarget(); } // Post a message so we dismiss after the above handlers are executed. mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface) .sendToTarget(); }
  • 68. Fix?
  • 69. Check the square blog Wrapper for clickListener and clear it on detach Or Send idle messages to clean app the messages https://corner.squareup.com/2015/08/a-small-leak.html
  • 71. Do not keep long-lived references to a context- activity public static Context mContext; public NoLifeCycleClass(Activity myActivity) { mContext = (Context) myActivity; }
  • 72. Try using the context-application instead of a context-activity StringUtilsUI.doSomeLongRunningTask(getApplicationContext());
  • 73. Avoid non-static inner classes public class DialogCountdown extends BaseDialogFragment { private class CountDownHandler extends Handler { //do some work } }
  • 74. Avoid non-static inner classes private static class CountDownHandler extends Handler { private final WeakReference<DialogCountdown> mDialogCountdownWeakReference; public CountDownHandler(DialogCountdown dialogCountdown) { super(); mDialogCountdownWeakReference = new WeakReference<>(dialogCountdown); } public void handleMessage(Message msg) { if(mDialogCountdownWeakReference.get()!=null) { mDialogCountdownWeakReference.get().onCountDown(); } }
  • 75. Clean/Stop all your handlers, animation listeners onDestroy(); protected void onStop() { super.onStop(); mHandler.clearAllMessages(); unregisterReceivers(); heatMapsDone(); if (mServiceBound) { mServiceBound = false; Services.unbindFromRidesService(this, this); } if (mMapStateMachine != null) { mMapStateMachine.stop(); mMapStateMachine = null; } }
  • 77.
  • 78. Today
  • 80. Jack
  • 81. Jill