Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Memory Management in Android

Introduction of Memory Management in Android App
by

Raymond Wu

on 8 October 2015

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Memory Management in Android

Memory
management
in
ANDROID

Raymond Wu 2014/02/11
Why should we need to know
how Android manages memory?
The more Apps Android can keep in memory, the faster it will be for the user to switch between his Apps
Memory Leak
A "memory leak" in your app is when you keep a reference to an object that is no longer needed.
It would cause a large set of objects from being garbage collected.
OOM!! (Out Of Memory Exception)
App Life cycle
memory allocation in java
Max heap size:
Runtime.getRuntime().maxMemory()
Allocated heap size:
Runtime.getRuntime().totalMemory()
Free heap size:
Runtime.getRuntime().freeMemory()
Unit of allocation in heap
Object!
Max heap size
S3: 64Mb HTC new one: 128Mb
int x = 777;
String mString = new String("Hello!~");
int [] y = {1, 2, 3};
An object is a class instance or an array
x is a primitive variable, mString and y are reference variables
Stack
Method area: class structures, code for methods, constants and
static variables
Stack:local variables, method parameter and function return address
Type of java variable
Primitive Type
byte
short
int
long
char
float
double
boolean
Reference Type
A point to class instance or array
VALUE!
mEMORY aDDRESS!
Example 1
Example 2
Garbage collection
Collector attempts to reclaim memory occupied by
objects in heap
that are no longer in use by the app
Mark-and-Sweep algorithm
Garbage collection
Original
Mark
Sweep
GC example 1
GC example 1
GC example 2
GC example 2
GC example 2
However, GC couldn't avoid from memory leak!
There are 3 reasons may cause memory leak
1. Context-related memory leak
2. Abuse of static modifier
3. Implicit reference of inner class
Context-related memory leak
Context is used for many operations but mostly to load and access resources
getContentResolver()
getPackageManager()
getSharedPreferences()
...
Context-related memory leak
sCachedDrawable (Drawable) -> mLable (TextView) -> Activity context (Activity)
A static sCachedDrawable variable holds the whole Activity indirectly!!
Context-related memory leak
Do not
keeping a long-lived reference to a
Activity-Context!
A reference to an activity should have the same life cycle as the activity itself
Solution:
Try using the
Application-Context
instead of an Activity-Context
Context.getApplicationContext()
Activity.getApplication()
Abuse of static modifier
When you declare a variable as a
static variable
.
It would be restored in method area of non-heap memory
forever
when the class loader loads the class.
mIcon -> MyActivity -> All variables of Activity The whole activity will be occupied in memory
Abuse of static modifier
When you declare a method as a
static method
.
You can use the method with Class name without creating instance.

java.lang.
Math.sqrt(num)
java.lang.
Runtime.totalMemory()
Static methods typically take all data from parameters and do some kind of generic calculation without reference to variables.
Abuse of static modifier
What will happen in the above code?
Compile Error:
Cannot make a static reference to the non-static field p
Abuse of static modifier
Solution:
Be
careful
to use static variable and method
Use static variable with
final
modifier
Use
binder
between Activity and Service
Use a Service and report the results back to the Activity by using a
BroadcastReceiver
Use
android.app.Application
class to restore global data
http://www.offthehill.org/articles/2011/06/03/java-static-variables-are-wrong-almost-always/
Implicit reference of inner class - Thread
Implicit reference of inner class
Better Performance
Debug faster
Make the world better, just like heaven
Make the world of Android better
Make users fall in love with Android
In Java, non-static anonymous classes hold a reference to their outer class
Thread ID: 19408
Thread ID: 19408
Thread ID: 19408
Thread ID: 19408
Thread ID: 19408
Thread ID: 19409
Thread ID: 19408
Thread ID: 19409
Thread ID: 19408
Thread ID: 19409
Thread ID: 19408
Thread ID: 19409
Thread ID: 19410
Thread ID: 19408
Thread ID: 19409
Thread ID: 19410
Thread ID: 19408
Thread ID: 19409
Thread ID: 19410
After screen rotating, infinite threads will hold each activity that creates them, cause memory leak!
Solution 1: Declare the thread as a private static inner class
BUT!! Threads are still running in background
Implicit reference of inner class
Solution 2: Implement cancellation policies for your background threads
Don't assume that Java will clean up your running threads for you
Implicit reference of inner class
Solution 3: Consider whether you should use a thread or not
Using a Loader/AsyncTasks(process image in background)/Executor instead of a thread
DDMS + Android Memory Analyzer Tool (MAT)
Implicit reference of inner class - handler
Android Lint warning:
In Android, Handler classes should be static or leaks might occur
Application main Looper (message queue) -> Runnable -> Handler -> Activity
Implicit reference of inner class - handler
Solution: static-inner class + WeakReference
Weak reference:
Maintain a reference to an object without preventing it from being garbage collected
If an object is only referenced by WeakReference, the object is eligible for GC
DDMS + Android Memory Analyzer Tool (MAT)
Shallow heap: the amount of memory consumed by one object
Retained heap
: the sum of the shallow heap size of all objects that would be removed when this object is garbage collected
I'm sorry!!
q & a
static
Full transcript