Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does onLowMemory Work on android?

Tags:

android

I would like to know how onLowMemory() function gets executed

for eg.

Say I have 3 activities each with their onLowMemory() functions overridden to clean up data from RAM. I also have 1 Application class which also overrides onLowMemory() to clean up some global state data.

Now lets say we go from activity A -> activity B -> activity C , and on activity C we run out of memory. My question is what happens after that?

From what I understand, onLowMemory() function of Activity C and Application class will get called, am I correct? Does onLowMemory() function of activity A and B gets called ?

Also I believe Activity A and B will be killed (since they are background activities), but before those activities are killed, do their respective onLowMemory() gets called?

like image 528
Anuj Tenani Avatar asked Sep 09 '11 10:09

Anuj Tenani


People also ask

How to Check low memory in Android?

The Memory Profiler in Android Studio helps you find and diagnose memory issues in the following ways: See how your app allocates memory over time. The Memory Profiler shows a realtime graph of how much memory your app is using, the number of allocated Java objects, and when garbage collection occurs.

What is garbage collector Android?

Garbage collectionA managed memory environment, like the ART or Dalvik virtual machine, keeps track of each memory allocation. Once it determines that a piece of memory is no longer being used by the program, it frees it back to the heap, without any intervention from the programmer.


2 Answers

When the phone's memory is low, the background processes will be killed by framework. If the last background process is killed, the framework will call onLowMemory of every app.

This is described in source codes. See: https://github.com/android/platform_frameworks_base/blob/master/services/java/com/android/server/am/ActivityManagerService.java#L3088

  // If there are no longer any background processes running,
  // and the app that died was not running instrumentation,
  // then tell everyone we are now low on memory.
like image 106
Yong Avatar answered Sep 20 '22 13:09

Yong


According to the Documentation http://developer.android.com/reference/android/app/Application.html#onLowMemory%28%29

the exact point at which this will be called is not defined, generally it will happen around the time all background process have been killed, that is before reaching the point of killing processes hosting service and foreground UI that we would like to avoid killing.

like image 27
Sujit Avatar answered Sep 19 '22 13:09

Sujit