Monitoring Memory Usage

edited February 2017 in Android Mode

Hi All I am trying to find a means of monitoring memory usage and ultimately would like to have a background thread that will warn users when an app's memory usage is in danger of reaching the heap limit. I currently use try/catch to deal with out of memory issues but now want to anticipate issues in advance if possible. So far I have the code below that gives me allocated heap size and system memory usage but I cannot find a way to just get heap usage for an app. Is there a straight forward way to do this? Mark

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo ;
import android.os.Environment;
import android.content.Context;

Activity activity ;
Context context ; 
MemoryInfo myMemInfo ;
ActivityManager myActivityManager ;
long heapSize ;

void setup() {
  fullScreen(P2D) ;
  activity = this.getActivity();  
  context = activity.getApplicationContext();
  heapSize = Runtime.getRuntime().maxMemory();
  myMemInfo = new MemoryInfo();
  myActivityManager = (ActivityManager) context.getSystemService(activity.ACTIVITY_SERVICE);
  fill(255); // text colour
  textAlign(CENTER, CENTER);
}

void draw() {
  background(0) ;
  displayMemInfo() ;
}// end draw()

void displayMemInfo() {
  myActivityManager.getMemoryInfo(myMemInfo) ;
  text("availMem = " + myMemInfo.availMem/1048576 + "MB" + "\n"
    + "appMemory = " + myActivityManager.getMemoryClass() + "MB" + "\n"
    + "lowMemory =  " + myMemInfo.lowMemory + "\n"
    + "threshold =  " + myMemInfo.threshold/1048576 + "MB" + "\n"
    + "heapSize = " + heapSize/1048576 + "MB" + "\n"
    , 0, 0, width, height);
}
Sign In or Register to comment.