Android Question Memory RAM

G-ShadoW

Active Member
Licensed User
Longtime User
How to get memory usage ( total, free, used )

I have found this java code since I didnt find anything similar here in forum, but I dont
know how to add this code in timer...

B4X:
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;

}
 

DonManfred

Expert
Licensed User
Longtime User
Use inline java

You can use the lines
B4X:
Dim usedmem As Long = nativeMe.RunMethod("getUsedMemorySize", Null)
    Log("UsedMEMORY = "&usedmem)
in a timer tick


B4X:
Sub Process_Globals
    Private nativeMe As JavaObject
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        nativeMe.InitializeContext
    End If
    Dim usedmem As Long = nativeMe.RunMethod("getUsedMemorySize", Null)
    Log("UsedMEMORY = "&usedmem)
    'Dim c As Class1
    'c.Initialize
    'StartService(Service1)
    'Code1.Init
    'Activity.AddMenuItem("Example1", "Example1")
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

#If JAVA
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;
}
#End IF

You need to check javaobject library...
 
Upvote 0

G-ShadoW

Active Member
Licensed User
Longtime User
B4X:
Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        nativeMe.InitializeContext
    End If
    Dim usedmem As Long = nativeMe.RunMethod("getUsedMemorySize", Null)
    Dim totalmem As Long = nativeMe.RunMethod("getTotalMemory", Null)
    Log("UsedMEMORY = "&usedmem)
    'Dim c As Class1
    'c.Initialize
    'StartService(Service1)
    'Code1.Init
    Timer1.Initialize("Timer1",1000)
    Timer1.Enabled=True
End Sub

B4X:
#If JAVA
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;
}

public static long getTotalMemory() {
    long freeSize = 0L;
    long totalSize = 0L;
    long usedSize = -1L;
    try {
        Runtime info = Runtime.getRuntime();
        totalSize = info.totalMemory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return usedSize;
}
public void _onCreate() {
    BA.Log("OnCreate");
}
public void _onResume() {
    BA.Log("OnResume");
}
public void _onPause() {
    BA.Log("onPause");
}
public void _onDestroy() {
    BA.Log("_onDestroy");
}
public void _onStop() {
    BA.Log("_onStop");
}
public void _onStart() {
    BA.Log("_onStart");
}
#End IF

Sub Timer1_tick
Dim usedmem As Long = nativeMe.RunMethod("getUsedMemorySize", Null)
    Log("UsedMEMORY = "&usedmem)
    Dim totalmem As Long = nativeMe.RunMethod("getTotalMemory", Null)
    Log("Total Memory = "&totalmem)
End Sub

this is what I get

UsedMEMORY = 8102504
Total Memory = -1
 
Upvote 0

G-ShadoW

Active Member
Licensed User
Longtime User
B4X:
#If JAVA
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;
}

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

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

public void _onCreate() {
    BA.Log("OnCreate");
}
public void _onResume() {
    BA.Log("OnResume");
}
public void _onPause() {
    BA.Log("onPause");
}
public void _onDestroy() {
    BA.Log("_onDestroy");
}
public void _onStop() {
    BA.Log("_onStop");
}
public void _onStart() {
    BA.Log("_onStart");
}
#End IF

Sub Timer1_tick
Dim usedmem As Long = nativeMe.RunMethod("getUsedMemorySize", Null)
    Log("UsedMEMORY = "&usedmem)
    Dim totalmem As Long = nativeMe.RunMethod("getTotalMemory", Null)
    Log("Total Memory = "&totalmem)
    Dim freemem As Long = nativeMe.RunMethod("getFreeMemory", Null)
    Log("Free Memory = " &freemem)
    End Sub

it's working now, one more question

this is code in activity create
B4X:
Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        nativeMe.InitializeContext
    End If
    Dim usedmem As Long = nativeMe.RunMethod("getUsedMemorySize", Null)
    Dim totalmem As Long = nativeMe.RunMethod("getTotalMemory", Null)
    Dim freemem As Long = nativeMe.RunMethod("getFreeMemory", Null)
    Log("UsedMEMORY = "&usedmem)
    'Dim c As Class1
    'c.Initialize
    'StartService(Service1)
    'Code1.Init
    Timer1.Initialize("Timer1",1000)
    Timer1.Enabled=True
End Sub

and even everything work's I have
warning #9
Unused variable 'totalmem'
Unused variable 'freemem'

how to fix that ?
 
Upvote 0

G-ShadoW

Active Member
Licensed User
Longtime User
This phone which I use have 768MB RAM
I have total RAM TotalMemory = 13635568 how to calculate this value to show 768 ?
BTW, any progress with webdav :D
 
Upvote 0

G-ShadoW

Active Member
Licensed User
Longtime User
If anyone need to check total available RAM using Inline java code, here is it...

B4X:
public String getTotalRAM() {

    RandomAccessFile reader = null;
    String load = null;
    DecimalFormat twoDecimalForm = new DecimalFormat("#.##");
    double totRam = 0;
    String lastValue = "";
    try {
        reader = new RandomAccessFile("/proc/meminfo", "r");
        load = reader.readLine();

        // Get the Number value from the string
        Pattern p = Pattern.compile("(\\d+)");
        Matcher m = p.matcher(load);
        String value = "";
        while (m.find()) {
            value = m.group(1);
            // System.out.println("Ram : " + value);
        }
        reader.close();

        totRam = Double.parseDouble(value);
        // totRam = totRam / 1024;

        double mb = totRam / 1024.0;
        double gb = totRam / 1048576.0;
        double tb = totRam / 1073741824.0;

        if (tb > 1) {
            lastValue = twoDecimalForm.format(tb).concat(" TB");
        } else if (gb > 1) {
            lastValue = twoDecimalForm.format(gb).concat(" GB");
        } else if (mb > 1) {
            lastValue = twoDecimalForm.format(mb).concat(" MB");
        } else {
            lastValue = twoDecimalForm.format(totRam).concat(" KB");
        }



    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        // Streams.close(reader);
    }

    return lastValue;
}
 
Upvote 0

Informatix

Expert
Licensed User
Longtime User
If anyone need to check total available RAM using Inline java code, here is it...

B4X:
public String getTotalRAM() {

    RandomAccessFile reader = null;
    String load = null;
    DecimalFormat twoDecimalForm = new DecimalFormat("#.##");
    double totRam = 0;
    String lastValue = "";
    try {
        reader = new RandomAccessFile("/proc/meminfo", "r");
        load = reader.readLine();

        // Get the Number value from the string
        Pattern p = Pattern.compile("(\\d+)");
        Matcher m = p.matcher(load);
        String value = "";
        while (m.find()) {
            value = m.group(1);
            // System.out.println("Ram : " + value);
        }
        reader.close();

        totRam = Double.parseDouble(value);
        // totRam = totRam / 1024;

        double mb = totRam / 1024.0;
        double gb = totRam / 1048576.0;
        double tb = totRam / 1073741824.0;

        if (tb > 1) {
            lastValue = twoDecimalForm.format(tb).concat(" TB");
        } else if (gb > 1) {
            lastValue = twoDecimalForm.format(gb).concat(" GB");
        } else if (mb > 1) {
            lastValue = twoDecimalForm.format(mb).concat(" MB");
        } else {
            lastValue = twoDecimalForm.format(totRam).concat(" KB");
        }



    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        // Streams.close(reader);
    }

    return lastValue;
}
Note that the Cache and StrictMode libraries have functions to compute max and free memory ACCORDING TO THE ANDROID VERSIONS because all the code above is only right for the recent versions (4+).
And that's only for the Java heap, not for the native memory. 768 MB on your device is the total size of the native memory, not the fraction available to your Java apps. I explained that many times so a search in the forum would give you all details.
 
Upvote 0

G-ShadoW

Active Member
Licensed User
Longtime User
Is there any b4a code that works for all android version's ( Total RAM - Used RAM and Left RAM )?
 
Upvote 0

Informatix

Expert
Licensed User
Longtime User
Is there any b4a code that works for all android version's ( Total RAM - Used RAM and Left RAM )?
Java code from my Cache library:
B4X:
     *Gets the maximum amount of memory (in bytes) that may be used by the running program.
     */
    public static long getMaxMemory()
    {
        Runtime r = java.lang.Runtime.getRuntime();
        return r.maxMemory();
    }

    /**
     *Gets an approximation of the amount (in bytes) of free memory available to the running program.
     */
    public static long getFreeMemory()
    {
        Runtime r = java.lang.Runtime.getRuntime();
        final long MM = r.maxMemory();        //maximum amount of memory that may be used by the running program
        final long TM = r.totalMemory();    //current heap size
        final long FM = r.freeMemory();        //free heap memory
        if (android.os.Build.VERSION.SDK_INT < 11)
        {
            // Before Honeycomb
            final long NA = android.os.Debug.getNativeHeapAllocatedSize();
            return Math.max(0, MM - TM + FM - NA);
        }
        else
            return Math.max(0, MM - TM + FM);
    }
 
Upvote 0
Top