null
null

Reputation: 98

how to determine when the device has low memory on Android

My app is a background service running in the foreground. In low memory situations some of my processing threads are being killed without the app being restarted. This is causing very strange behavior. I would like to be alerted by the OS when the memory is low before my process are killed. This will allow me to release memory or restart my app. I can't seem to find a broadcast or notification for this situation.

Upvotes: 2

Views: 6851

Answers (2)

D Walker
D Walker

Reputation: 167

I suggest you read "Managing Your App's Memory" here: https://developer.android.com/training/articles/memory.html. The system callback method onTrimMemory will inform you of different RAM usage scenarios as indicated by the value of the method argument. See https://developer.android.com/reference/android/content/ComponentCallbacks2.html#onTrimMemory(int) for details. This method's description says:

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process. This will happen for example when it goes in the background and there is not enough memory to keep as many background processes running as desired. You should never compare to exact values of the level, since new intermediate values may be added -- you will typically want to compare if the value is greater or equal to a level you are interested in.

To retrieve the processes current trim level at any point, you can use ActivityManager.getMyMemoryState(RunningAppProcessInfo).

For example, TRIM_MEMORY_COMPLETE as an argument to onTrimMemory:

public static final int TRIM_MEMORY_COMPLETE Level for onTrimMemory(int): the process is nearing the end of the background LRU list, and if more memory isn't found soon it will be killed. Constant Value: 80 (0x00000050)

Upvotes: 2

Wish
Wish

Reputation: 44

  1. There is one background service “DeviceStorageMonitorService” continuously running inside Android, which checks system storage directory periodically.
  2. This service maintains a memory threshold which is 10% of the assigned internal system memory, so in case of P2 it is 861MB, so memory threshold is 86 MB. We can change this by changing macro DEFAULT_THRESHOLD_PERCENTAGE inside file DeviceStorageMonitorService.java.
  3. It checks the size of available memory with the memory threshold, if it is less than threshold memory, it will broadcast notification and sticky broadcast intent ACTION_DEVICE_STORAGE_LOW. In case of full memory intent ACTION_DEVICE_STORAGE_FULL

Receive this broadcasted intent in your receiver and handle the application.

Upvotes: 2

Related Questions