Skip to content

Instantly share code, notes, and snippets.

@SurajBahadur
Created January 16, 2023 04:55
Show Gist options
  • Save SurajBahadur/dfceebed1296c33607de180202e050b8 to your computer and use it in GitHub Desktop.
Save SurajBahadur/dfceebed1296c33607de180202e050b8 to your computer and use it in GitHub Desktop.
During any stage of your app's lifecycle, the onTrimMemory() callback also tells you when the overall device memory is getting low. You should respond by further releasing resources based on the following memory levels delivered by onTrimMemory(), This gist allows you to log the different states.
@Override
public void onTrimMemory(int level) {
Map<Integer, String> constantMap = getConstantMap();
switch (level) {
case TRIM_MEMORY_RUNNING_MODERATE:
Log.e(TAG, getConstantName(constantMap, TRIM_MEMORY_RUNNING_MODERATE));
break;
case TRIM_MEMORY_RUNNING_LOW:
Log.e(TAG, getConstantName(constantMap, TRIM_MEMORY_RUNNING_LOW));
break;
case TRIM_MEMORY_RUNNING_CRITICAL:
Log.e(TAG, getConstantName(constantMap, TRIM_MEMORY_RUNNING_CRITICAL));
break;
case TRIM_MEMORY_UI_HIDDEN:
Log.e(TAG, getConstantName(constantMap, TRIM_MEMORY_UI_HIDDEN));
break;
case TRIM_MEMORY_BACKGROUND:
Log.e(TAG, getConstantName(constantMap, TRIM_MEMORY_BACKGROUND));
break;
case TRIM_MEMORY_MODERATE:
Log.e(TAG, getConstantName(constantMap, TRIM_MEMORY_MODERATE));
break;
case TRIM_MEMORY_COMPLETE:
Log.e(TAG, getConstantName(constantMap, TRIM_MEMORY_COMPLETE));
break;
default:
Log.e(TAG, "Default Case Hit!");
break;
}
}
private static Map<Integer, String> getConstantMap() {
Map<Integer, String> constantMap = new HashMap<>();
for (Field field : ComponentCallbacks2.class.getDeclaredFields()) {
if (((field.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) != 0) && int.class == field.getType()) {
// only record final static int fields
try {
constantMap.put(field.getInt(null), field.getName());
} catch (IllegalAccessException e) {
Log.e(TAG, e.getMessage());
}
}
}
return constantMap;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment