Android Tutorial - Hardware : Memory

 Get memory information

  

package app.test;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;

class CMDExecute {

  public synchronized String run(String[] cmd, String workdirectory)
      throws IOException {
    String result = "";

    try {
      ProcessBuilder builder = new ProcessBuilder(cmd);
      // set working directory
      if (workdirectory != null)
        builder.directory(new File(workdirectory));
      builder.redirectErrorStream(true);
      Process process = builder.start();
      InputStream in = process.getInputStream();
      byte[] re = new byte[1024];
      while (in.read(re) != -1) {
        System.out.println(new String(re));
        result = result + new String(re);
      }
      in.close();

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return result;
  }

}

public class Main {
  private static StringBuffer buffer;

  public static String getMemoryInfo(Context context) {
    StringBuffer memoryInfo = new StringBuffer();
    final ActivityManager activityManager = (ActivityManager) context
        .getSystemService(Context.ACTIVITY_SERVICE);

    ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(outInfo);
    memoryInfo.append("\nTotal Available Memory :")
        .append(outInfo.availMem >> 10).append("k");
    memoryInfo.append("\nTotal Available Memory :")
        .append(outInfo.availMem >> 20).append("M");
    memoryInfo.append("\nIn low memory situation:").append(
        outInfo.lowMemory);

    String result = null;
    CMDExecute cmdexe = new CMDExecute();
    try {
      String[] args = { "/system/bin/cat", "/proc/meminfo" };
      result = cmdexe.run(args, "/system/bin/");
    } catch (IOException ex) {
      Log.i("fetch_process_info", "ex=" + ex.toString());
    }

    return memoryInfo.toString() + "\n\n" + result;
  }
}

Get Memory Size Strings

  
import java.text.DecimalFormat;

class Main{

    /**
     * 
     * @return
     */
    public static String getMemorySizeStrings() {
        
        DecimalFormat dformat = new DecimalFormat("###,###,###,##0");
        String mem = null;
        long freeSize = 0L;
        long totalSize = 0L;
        long usedSize = 0L;
        try {
            Runtime info = Runtime.getRuntime();
            freeSize = info.freeMemory();
            totalSize = info.totalMemory();
            usedSize = totalSize - freeSize;

            mem = "free=" + dformat.format(freeSize) + " byte / " + "total="
                    + dformat.format(totalSize) + " byte / " + "used="
                    + dformat.format(usedSize) + " byte";

        } catch (Exception e) {
            e.printStackTrace();
        }
        return mem;
    }
}

Get Used Memory Size

  
import java.text.DecimalFormat;

class Main{

    /**
     * 
     * @return
     */
    public static long getUsedMemorySize() {

        long freeSize = 0L;
        long totalSize = 0L;
        long usedSize = -1L;
        try {
            Runtime info = Runtime.getRuntime();
            freeSize = info.freeMemory();
            totalSize = info.totalMemory();
            usedSize = totalSize - freeSize;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return usedSize;

    }

}

Get Free Memory Size

  
import java.text.DecimalFormat;

class Main{
    /***
     * 
     * @return
     */
    public static long getFreeMemorySize() {
        
        long size = -1L;
        try {
            Runtime info = Runtime.getRuntime();
            size = info.freeMemory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

}

Get Total Memory Size

  
import java.text.DecimalFormat;

class Main{
    /**
     *  
     */
    public static long getTotalMemorySize() {
        
        long size = -1L;
        try {
            Runtime info = Runtime.getRuntime();
            size = info.totalMemory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

}

Calculates the free memory of the device. This is based on an inspection of the filesystem, which in android devices is stored in RAM.

  
//package org.acra.util;

import java.io.File;


import android.content.Context;
import android.content.res.Configuration;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

/**
 * Responsible for providing base utilities used when constructing the report.
 * <p/>
 * @author William Ferguson
 * @since 4.3.0
 */
public final class ReportUtils {

    /**
     * Calculates the free memory of the device. This is based on an inspection of the filesystem, which in android
     * devices is stored in RAM.
     *
     * @return Number of bytes available.
     */
    public static long getAvailableInternalMemorySize() {
        final File path = Environment.getDataDirectory();
        final StatFs stat = new StatFs(path.getPath());
        final long blockSize = stat.getBlockSize();
        final long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

}

Calculates the total memory of the device. This is based on an inspection of the filesystem, which in android devices is stored in RAM.

  
//package org.acra.util;

import java.io.File;


import android.content.Context;
import android.content.res.Configuration;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

public final class ReportUtils {

    public static long getTotalInternalMemorySize() {
        final File path = Environment.getDataDirectory();
        final StatFs stat = new StatFs(path.getPath());
        final long blockSize = stat.getBlockSize();
        final long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }
}

Get Memory Total

  
//package org.anddev.andengine.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Scanner;
import java.util.regex.MatchResult;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;

/**
 * (c) 2010 Nicolas Gramlich 
 * (c) 2011 Zynga Inc.
 * 
 * @author Nicolas Gramlich
 * @since 15:50:31 - 14.07.2010
 */
class SystemUtils {
  private static final String BOGOMIPS_PATTERN = "BogoMIPS[\\s]*:[\\s]*(\\d+\\.\\d+)[\\s]*\n";
  private static final String MEMTOTAL_PATTERN = "MemTotal[\\s]*:[\\s]*(\\d+)[\\s]*kB\n";
  private static final String MEMFREE_PATTERN = "MemFree[\\s]*:[\\s]*(\\d+)[\\s]*kB\n";


  /**
   * @return in kiloBytes.
   * @throws SystemUtilsException
   */
  public static int getMemoryTotal() throws Exception {
    final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", MEMTOTAL_PATTERN, 1000);

    try {
      if(matchResult.groupCount() > 0) {
        return Integer.parseInt(matchResult.group(1));
      } else {
        throw new Exception();
      }
    } catch (final NumberFormatException e) {
      throw new Exception(e);
    }
  }

  private static MatchResult matchSystemFile(final String pSystemFile, final String pPattern, final int pHorizon) throws Exception {
    InputStream in = null;
    try {
      final Process process = new ProcessBuilder(new String[] { "/system/bin/cat", pSystemFile }).start();

      in = process.getInputStream();
      final Scanner scanner = new Scanner(in);

      final boolean matchFound = scanner.findWithinHorizon(pPattern, pHorizon) != null;
      if(matchFound) {
        return scanner.match();
      } else {
        throw new Exception();
      }
    } catch (final IOException e) {
      throw new Exception(e);
    } 
      
  }
}

Get Memory Free

  

//package org.anddev.andengine.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Scanner;
import java.util.regex.MatchResult;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;

/**
 * (c) 2010 Nicolas Gramlich 
 * (c) 2011 Zynga Inc.
 * 
 * @author Nicolas Gramlich
 * @since 15:50:31 - 14.07.2010
 */
class SystemUtils {
  private static final String BOGOMIPS_PATTERN = "BogoMIPS[\\s]*:[\\s]*(\\d+\\.\\d+)[\\s]*\n";
  private static final String MEMTOTAL_PATTERN = "MemTotal[\\s]*:[\\s]*(\\d+)[\\s]*kB\n";
  private static final String MEMFREE_PATTERN = "MemFree[\\s]*:[\\s]*(\\d+)[\\s]*kB\n";


  /**
   * @return in kiloBytes.
   * @throws SystemUtilsException
   */
  public static int getMemoryFree() throws Exception {
    final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", MEMFREE_PATTERN, 1000);

    try {
      if(matchResult.groupCount() > 0) {
        return Integer.parseInt(matchResult.group(1));
      } else {
        throw new Exception();
      }
    } catch (final NumberFormatException e) {
      throw new Exception(e);
    }
  }
  private static MatchResult matchSystemFile(final String pSystemFile, final String pPattern, final int pHorizon) throws Exception {
    InputStream in = null;
    try {
      final Process process = new ProcessBuilder(new String[] { "/system/bin/cat", pSystemFile }).start();

      in = process.getInputStream();
      final Scanner scanner = new Scanner(in);

      final boolean matchFound = scanner.findWithinHorizon(pPattern, pHorizon) != null;
      if(matchFound) {
        return scanner.match();
      } else {
        throw new Exception();
      }
    } catch (final IOException e) {
      throw new Exception(e);
    } 
      
  }
}

get MemoryInfo

  

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;

 class Utils {
    
    public static MemoryInfo getMemoryInfo(Context _context) {
      MemoryInfo info = new MemoryInfo();
      getActivityManager(_context).getMemoryInfo(info);
      return info;
    }
    public static ActivityManager getActivityManager(Context context)
    {
      ActivityManager result = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
      if (result == null)
        throw new UnsupportedOperationException("Could not retrieve ActivityManager");
      return result;
    }
}

Memory information

  
//package org.beryl.util;

import java.util.Locale;

public class Memory {

  public static final long KB_IN_BYTES = 1024;
  public static final long MB_IN_BYTES = 1024 * KB_IN_BYTES;
  public static final long GB_IN_BYTES = 1024 * MB_IN_BYTES;
  public static final long TB_IN_BYTES = 1024 * GB_IN_BYTES;

  public static final long FOUR_MB_IN_BYTES = 4 * MB_IN_BYTES;

  final static long [] sizeArray = { TB_IN_BYTES, GB_IN_BYTES, MB_IN_BYTES, KB_IN_BYTES, 1 };
  final static String [] sizeUnitsArray = { "TB", "GB", "MB", "KB", "bytes" };

  public static long getReasonableMemoryCushion() {
    return FOUR_MB_IN_BYTES;
  }

  public static long bytesToKilobytes(long bytes) {
    return bytes / KB_IN_BYTES;
  }

  public static long bytesToMegabytes(long bytes) {
    return bytes / MB_IN_BYTES;
  }

  public static long bytesToGigabytes(long bytes) {
    return bytes / GB_IN_BYTES;
  }

  public static long bytesToTerabytes(long bytes) {
    return bytes / TB_IN_BYTES;
  }

  public static long freeMemory() {
    final Runtime rt = Runtime.getRuntime();
    return rt.freeMemory();
  }

  public static long memoryLimit() {
    final Runtime rt = Runtime.getRuntime();
    return rt.maxMemory();
  }

  public static double consumptionRatio() {
    return freeMemory() / (double)memoryLimit();
  }

  public static String toString(long bytes) {
    String byteSizeString = "<unknown> bytes";
    final int length = sizeArray.length;
    double size;
    double dBytes = (double) bytes;

    for(int i = 0; i < length; i++) {
      size = dBytes / sizeArray[i];

      if(size >= 1.0) {
        byteSizeString = String.format(Locale.ENGLISH, "%.4f %s", size, sizeUnitsArray[i]);
        break;
      }
    }

    return byteSizeString;
  }
}