Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get total device ram?I need it for an optimization

Tags:

android

I have a lrucache that could contain static data, so that even if my app is closed when user returns he can find data faster.

However this takes about 10-15 MB of memory and so I'd like to make an if branch like this

if(deviceOverallRAM > treshold)
      preserve static memory on app exit
else
      clear static memory on app exit

So, can I get device's ram, maybe through some hidden api? And what would be a good value for the treshold?

like image 286
Phate Avatar asked Sep 23 '12 10:09

Phate


People also ask

What happens when RAM is full on Android?

Your phone will slow down. Yes, it results in a slow Android phone. To be specific, a full RAM would make switching from one app to another to be like waiting for a snail to cross a road. Plus, some apps will slow down, and in some frustrating cases, your phone will freeze.


1 Answers

To do this pre-API 16 you have to read the proc/meminfo file of the android kernel:

 public long getTotalMemory() {  

    String str1 = "/proc/meminfo";
    String str2;        
    String[] arrayOfString;
    long initial_memory = 0;
    try {
    FileReader localFileReader = new FileReader(str1);
    BufferedReader localBufferedReader = new BufferedReader(    localFileReader, 8192);
    str2 = localBufferedReader.readLine();//meminfo
    arrayOfString = str2.split("\\s+");
    for (String num : arrayOfString) {
    Log.i(str2, num + "\t");
    }
    //total Memory
    initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;   
    localBufferedReader.close();
    return initial_memory;
    } 
    catch (IOException e) 
    {       
        return -1;
    }
  }  

Source: this question

However, in API 16 and onward, you can use the following code to retrieve the total memory:

ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
long totalMemory = memInfo.totalMem;
like image 107
Leon Lucardie Avatar answered Oct 31 '22 18:10

Leon Lucardie