How to get Android RAM, Internal and External Memory Information

How to get Android RAM, Internal and External Memory Information

In this tutorial, we are going to learn how to get RAM, Internal and External Memory information in our android application project. There are many situations in which we might want to check the amount of free or available memory in our device. We can also determine the free space in our external storage if you are planning to install or save huge file in our external storage.

In this tutorial, we will make use of ListView and each item of the ListView will hold information about a particular memory.

We will focus on the RAM, Internal and External storage. Each memory will be represented in three information – Used, Free and Total.

The ListView will be use a BaseAdapter subclass which will in turn inflate a layout file. In order to understand it much better, we are going to show a screen shot of what we will achieve in this tutorial as shown below.

android memory

Before we start, it is important for you to understand the tools and environment I used in this application. Feel free to use any tools you are familiar with.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidMemory

Package: com.inducesmile.androidmemory

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

If you are using Android Studio as your choice IDE, the new project will create a default MainActivity.java file and the corresponding layout file. Open the two files because we are going to make use of it soon.

In our project main layout file, add a ListView control that will hold all the information about our device.

Copy and paste the following code in activty_main.xml. The ListView is add in a RelativeLayout GroupView.

<RelativeLayout 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"
    tools:context="inducesmile.com.completeandroid.MemoryFragment">

    <ListView
        android:id="@+id/list_of_memory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:listSelector="@android:color/transparent"
        android:scrollbars="none" />

</RelativeLayout>

Now that we are done with our layout file, we will focus on the adapter class which will use our data source contain and bind it to the ListView items. The adapter class use the ViewHolder pattern to bind each View component to its respective data. The code snippet for our Adapter subclass is as shown.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class MemoryAdapter extends BaseAdapter {

    private LayoutInflater layoutInflater;
    private List<Memory> listStorage;

    public MemoryAdapter(Context context, List<Memory> customizedListView) {
        layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        listStorage = customizedListView;
    }

    @Override
    public int getCount() {
        return listStorage.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder listViewHolder;
        if(convertView == null){
            listViewHolder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.memory_list, parent, false);

            listViewHolder.heading = (TextView)convertView.findViewById(R.id.memory_title);
            listViewHolder.usedSpace = (TextView)convertView.findViewById(R.id.used_space);
            listViewHolder.freeSpace = (TextView)convertView.findViewById(R.id.free_space);
            listViewHolder.totalSpace = (TextView)convertView.findViewById(R.id.total_space);
            listViewHolder.imageIcon = (ImageView)convertView.findViewById(R.id.pie_image);

            convertView.setTag(listViewHolder);
        }else{
            listViewHolder = (ViewHolder)convertView.getTag();
        }
        listViewHolder.heading.setText(listStorage.get(position).getTitle());
        listViewHolder.usedSpace.setText(listStorage.get(position).getUsedSpace());
        listViewHolder.freeSpace.setText(listStorage.get(position).getFreeSpace());
        listViewHolder.totalSpace.setText(listStorage.get(position).getTotalSpace());
        listViewHolder.imageIcon.setImageResource(listStorage.get(position).getImage());

        return convertView;
    }

    static class ViewHolder{

        TextView heading;
        TextView usedSpace;
        TextView freeSpace;
        TextView totalSpace;
        ImageView imageIcon;
    }
}

The inflate layout file in our adapter class is name memory_list.xml. We are going to create this file in our project layout file. Once you are done with it, open the layout file and copy and paste the code in it.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="32dp">

    <TextView
        android:id="@+id/memory_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#5D4037"
        android:padding="16dp"
        android:textSize="17sp"
        android:textColor="#000000"
        android:text="@string/hello_world"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/memory_title"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:paddingBottom="16dp"
        android:orientation="horizontal">

        <LinearLayout
            android:id="@+id/left_column"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/pie_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:contentDescription="@string/hello_world" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/right_column"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TableLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/solvent_image"
                android:layout_marginTop="16dp"
                android:stretchColumns="1">

                <TableRow>

                    <TextView
                        android:layout_width="60dp"
                        android:layout_height="match_parent"
                        android:padding="8dp"
                        android:text="@string/hello_world"
                        android:textColor="#000"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/used_space"
                        android:layout_width="50dp"
                        android:layout_height="match_parent"
                        android:padding="8dp"
                        android:textStyle="bold"
                        android:text="@string/free_space"
                        android:textColor="#000" />
                </TableRow>

                <TableRow>

                    <TextView
                        android:layout_width="60dp"
                        android:padding="8dp"
                        android:text="@string/free"
                        android:textColor="#000"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/free_space"
                        android:layout_width="0dp"
                        android:padding="8dp"
                        android:text="@string/free_space"
                        android:textStyle="bold"
                        android:textColor="#000" />
                </TableRow>

                <TableRow>

                    <TextView
                        android:layout_width="60dp"
                        android:padding="8dp"
                        android:text="@string/total"
                        android:textColor="#000"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/total_space"
                        android:layout_width="20dp"
                        android:padding="8dp"
                        android:textStyle="bold"
                        android:text="@string/free_space"
                        android:textColor="#000" />
                </TableRow>

            </TableLayout>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

The memory_list.xml file paste above looks simple. It is a bunch of View controls arranged with different layout GroupViewws.

We will create an entity class which will hold information but each kind of memory. The Memory class has five parameters and each of the parameters will be displayed in the memory information it represents. The code for the class is as shown.

package com.inducesmile.henry.memory;

public class Memory {

    private String title;
    private String usedSpace;
    private String freeSpace;
    private String totalSpace;
    private int image;

    public Memory(String title, String usedSpace, String freeSpace, String totalSpace, int image) {
        this.title = title;
        this.usedSpace = usedSpace;
        this.freeSpace = freeSpace;
        this.totalSpace = totalSpace;
        this.image = image;
    }

    public String getTitle() {
        return title;
    }

    public String getUsedSpace() {
        return usedSpace;
    }

    public String getFreeSpace() {
        return freeSpace;
    }

    public String getTotalSpace() {
        return totalSpace;
    }

    public int getImage() {
        return image;
    }
}

The final code we will work on to finish off with this tutorial is to update our MainActivity.java file. In our MainActivity class, we will get the holder for the ListView in activity_main.xml layout file. The setAdapter() method of the class is called and we will pass an instance of the Adapter class to it.

The adapter class accepts two parameter, the first is the application context and the second is the data source.

package com.inducesmile.henry.memory;

import android.app.Activity;
import android.app.ActivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity {

    private String TAG = getClass().getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView memoryList = (ListView)findViewById(R.id.list_of_memory);

        List<Memory> memoryDataSource = new ArrayList<Memory>();

        String heading = "RAM Information";
        long totalRamValue = totalRamMemorySize();
        long freeRamValue = freeRamMemorySize();
        long usedRamValue = totalRamValue - freeRamValue;
        int imageIcon = R.drawable.piechart;

        Memory mMemory = new Memory(heading, formatSize(usedRamValue) + " MB", formatSize(freeRamValue) + " MB", formatSize(totalRamValue) + " MB", imageIcon);
        memoryDataSource.add(mMemory);

        String internalMemoryTitle = "Internal Memory Information";
        long totalInternalValue = getTotalInternalMemorySize();
        long freeInternalValue = getAvailableInternalMemorySize();
        long usedInternalValue = totalInternalValue - freeInternalValue;
        int internalIcon = R.drawable.piechartone;

        Memory internalMemory = new Memory(internalMemoryTitle, formatSize(usedInternalValue), formatSize(freeInternalValue), formatSize(totalInternalValue), internalIcon);
        memoryDataSource.add(internalMemory);

        String externalMemoryTitle = "External Memory Information";
        long totalExternalValue = getTotalExternalMemorySize();
        long freeExternalValue = getAvailableExternalMemorySize();
        long usedExternalValue = totalExternalValue - freeExternalValue;
        int externalIcon = R.drawable.piecharttwo;

        Memory externalMemory = new Memory(externalMemoryTitle, formatSize(usedExternalValue), formatSize(freeExternalValue), formatSize(totalExternalValue), externalIcon);
        memoryDataSource.add(externalMemory);

        MemoryAdapter memoryAdapter = new MemoryAdapter(MainActivity.this, memoryDataSource);
        memoryList.setAdapter(memoryAdapter);

    }

    private long freeRamMemorySize() {
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);
        long availableMegs = mi.availMem / 1048576L;

        return availableMegs;
    }

    private long totalRamMemorySize() {
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);
        long availableMegs = mi.totalMem / 1048576L;
        return availableMegs;
    }

    public static boolean externalMemoryAvailable() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    public static long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

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

    public static long getAvailableExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return availableBlocks * blockSize;
        } else {
            return 0;
        }
    }

    public static long getTotalExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return totalBlocks * blockSize;
        } else {
            return 0;
        }
    }

    public static String formatSize(long size) {
        String suffix = null;

        if (size >= 1024) {
            suffix = " KB";
            size /= 1024;
            if (size >= 1024) {
                suffix = " MB";
                size /= 1024;
            }
        }
        StringBuilder resultBuffer = new StringBuilder(Long.toString(size));

        int commaOffset = resultBuffer.length() - 3;
        while (commaOffset > 0) {
            resultBuffer.insert(commaOffset, ',');
            commaOffset -= 3;
        }
        if (suffix != null) resultBuffer.append(suffix);
        return resultBuffer.toString();
    }

    private String returnToDecimalPlaces(long values){
        DecimalFormat df = new DecimalFormat("#.00");
        String angleFormated = df.format(values);
        return angleFormated;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Now, when you run your application you will see the interface that looks similar to the sample that was shown earlier on.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published.

If you like this tutorial, please kindly download my new android app in Google play store by clicking the image below

OTHER INTERESTING POSTS:

3 Comments

Add a Comment