Get total and available memory in Delphi on Android

Viewed 201

Looking for Delphi code to check total and available memory (RAM) in my FMX app.

Is there a platform independent way? Can't find anything.

But that's just nice to have, in fact I only need it for Android.

2 Answers

This is just for Android and works well, tested with multiple devices and Delphi 10.3.3.

{$IFDEF ANDROID}
uses
  Androidapi.Helpers,
  Androidapi.JNIBridge,
  Androidapi.JNI.GraphicsContentViewText,
  Androidapi.JNI.App;

var
  MemoryInfo: JActivityManager_MemoryInfo;
begin
  MemoryInfo:= TJActivityManager_MemoryInfo.JavaClass.init;
  TJActivityManager.Wrap((TAndroidHelper.Context.getSystemService(
    TJContext.JavaClass.ACTIVITY_SERVICE) as ILocalObject).GetObjectID)
    .getMemoryInfo(MemoryInfo);
  TotalMb:= MemoryInfo.totalMem shr 20;
  AvailMb:= MemoryInfo.availMem shr 20;
end;
{$ENDIF}

A platform independent solution would still be nice...

They deprecated TAndroidHelper.Context in Delphi 11 from Delphi XE SharedActivityContext in file Androidapi.Helpers.pas. A program called SmartSynchronize helped alot in finding it. I used it to compare the differences between the 2 files. It's free for non-commerical use. All I do is write freeware. :P

This is maf-soft's answer modified to work with Delphi XE8

uses
  Androidapi.Helpers,
  Androidapi.JNIBridge,
  Androidapi.JNI.GraphicsContentViewText,
  Androidapi.JNI.App;




function AndroidGetTotalMemory: Int64;
var
  MemoryInfo: JActivityManager_MemoryInfo;
begin
  MemoryInfo:= TJActivityManager_MemoryInfo.JavaClass.init;

  TJActivityManager.Wrap((SharedActivityContext.getSystemService(
    TJContext.JavaClass.ACTIVITY_SERVICE) as ILocalObject).GetObjectID)
    .getMemoryInfo(MemoryInfo);
  result := MemoryInfo.totalMem shr 20; // in MB
end;


function AndroidGetAvailMemory: Int64;
var
  MemoryInfo: JActivityManager_MemoryInfo;
begin
  MemoryInfo:= TJActivityManager_MemoryInfo.JavaClass.init;

  TJActivityManager.Wrap((SharedActivityContext.getSystemService(
    TJContext.JavaClass.ACTIVITY_SERVICE) as ILocalObject).GetObjectID)
    .getMemoryInfo(MemoryInfo);
  result := MemoryInfo.availMem shr 20; //in MB
end;
Related