Tuesday, March 31, 2015

Get memory info

Example to get memory information using MemoryInfo and Runtime.


Where:

  • MemoryInfo.availMem: the available memory on the system.
  • MemoryInfo.totalMem: the total memory accessible by the kernel.
  • Runtime.maxMemory(): the maximum number of bytes the heap can expand to.
  • Runtime.totalMemory(): the current number of bytes taken by the heap.
  • Runtime.freeMemory(): the current number of those bytes actually used by live objects.


package com.example.androidmeminfo;

import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

 TextView textMemInfo;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textMemInfo = (TextView) findViewById(R.id.txmeminfo);
  textMemInfo.setText(getMemInfo());
 }

 private String getMemInfo() {
  MemoryInfo memoryInfo = new MemoryInfo();
  ActivityManager activityManager = 
   (ActivityManager) getSystemService(ACTIVITY_SERVICE);
  activityManager.getMemoryInfo(memoryInfo);
  
  Runtime runtime = Runtime.getRuntime();


  String strMemInfo = 
   "MemoryInfo.availMem = " + memoryInfo.availMem + "\n"
   + "MemoryInfo.totalMem = " + memoryInfo.totalMem + "\n" // API 16
   + "\n"
   + "Runtime.maxMemory() = " + runtime.maxMemory() + "\n"
   + "Runtime.totalMemory() = " + runtime.totalMemory() + "\n"
   + "Runtime.freeMemory() = " + runtime.freeMemory() + "\n";
  
  return strMemInfo;
 }

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidmeminfo.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/txmeminfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

No comments: