How Android obtains information such as total phone memory and available memory _android

Source: Internet
Author: User
Tags cpu usage

In Android development, sometimes we want to get some hardware information about the phone, such as the total memory and available memory size of the Android phone.

How does this happen?

By reading the file "/proc/meminfo" information can get the total number of mobile phone memory, and through the Activitymanager.getmemoryinfo ( Activitymanager.memoryinfo) method to get the current amount of available memory.
The "/proc/meminfo" file records some memory information about the Android phone, enters the "adb shell" into the shell environment and enters the "Cat/proc/meminfo" in the Command line window. You can display the contents of the Meminfo file on the command line

The details are shown below.

C:\USERS\FIGO>ADB Shell

# Cat/proc/meminfo

Cat/proc/meminfo

memtotal: 94096 KB

Memfree: 1684 KB

buffers: KB

Cached: 27160 KB

swapcached: 0 KB

Active: 35392 KB

Inactive: 44180 KB

Active (anon): 26540 KB

Inactive (anon): 28244 KB

Active (file): 8852 KB

Inactive (file): 15936 KB

unevictable: 280 KB

mlocked: 0 KB

swaptotal: 0 KB

Swapfree: 0 KB

Dirty: 0 KB

writeback: 0 KB

anonpages: 52688 KB

mapped: 17960 KB

Slab: 3816 KB

sreclaimable: 936 KB

sunreclaim: 2880 KB

pagetables: 5260 KB

nfs_unstable: 0 KB

Bounce: 0 KB

writebacktmp: 0 KB

commitlimit: 47048 KB

committed_as: 1483784 KB

vmalloctotal: 876544 KB

vmallocused: 15456 KB

vmallocchunk: 829444 KB

#

The following is a rough explanation of the fields listed in the "/proc/meminfo" file:

memtotal: all available RAM sizes.

Memfree: The sum of Lowfree and Highfree is left unused memory by the system.

Buffers: Used to buffer the file size.

Cached: The size of the memory (equal to DiskCache minus Swapcache) that is used by the cache memory (cache memory).

swapcached: the size of the swap space used by the buffer cache (cache memory). The memory that has been swapped out is still stored in the swapfile to be replaced quickly when needed without having to open the I/O port again.

Active: the size of the paging file in the active use of the buffer or cache, unless very necessary, will not be removed for his use.

Inactive: The size of the paging file in the infrequently used buffer or cache may be used in other ways.

swaptotal: The total size of the swap space.

Swapfree: the size of the swap space is not used.

Dirty: The amount of memory waiting to be written back to disk.

writeback: The memory size that is being written back to the disk.

anonpages: The memory size of the unmapped page.

Mapped: the size of mappings such as devices and files.

Slab: The size of the kernel data structure cache can reduce the cost of applying and freeing memory.

sreclaimable: the size of the slab can be recovered.

Sunreclaim: slab Size (Sunreclaim+sreclaimable=slab) is not recoverable.

Pagetables: manages the size of the index table for memory paging pages.

nfs_unstable: The size of the page table that is not stable.

To get the total memory size of the Android phone, simply read the 1th line of the "/proc/meminfo" file and do a simple string processing.

The following directly give detailed steps, we can according to the actual situation of the corresponding expansion.

1. New project, modify Main.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:orientation=" vertical " 
  android:layout_width=" fill_parent " 
  android:layout_" height= "Fill_parent" > 
<textview  
  android:layout_width= "Fill_parent"  
  Wrap_content "  
  android:textstyle=" bold " 
  android:id=" @+id/system_memory "/> 

2. Perfect Readsystemmemory.java class

Package com.figo.readsyememory; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Java.io.BufferedReader; 
Import Java.io.FileReader; 
Import java.io.IOException; 
Import Android.app.ActivityManager; 
Import Android.app.ActivityManager.MemoryInfo; 
Import Android.content.Context; 
Import Android.text.format.Formatter; 
Import Android.util.Log; 
 
Import Android.widget.TextView; 
 
  public class Readsystemmemory extends activity {TextView TV = null; Private String Getavailmemory () {//Get Android Current available memory size activitymanager am = (activitymanager) Getsystemservice (conte Xt. 
    Activity_service); 
    Memoryinfo mi = new Memoryinfo (); 
    Am.getmemoryinfo (MI); Mi.availmem; The current system's available memory return Formatter.formatfilesize (Getbasecontext (), mi.availmem);//The memory size to be acquired normalized} private String ge 
    Ttotalmemory () {String str1 = "/proc/meminfo";//system memory information file string str2; 
    String[] arrayofstring; 
 
    Long initial_memory = 0; try {FilereadEr localfilereader = new FileReader (STR1); 
      BufferedReader localbufferedreader = new BufferedReader (Localfilereader, 8192); 
      STR2 = Localbufferedreader.readline ()//Read Meminfo first row, system total memory size arrayofstring = Str2.split ("\\s+"); 
      for (String num:arrayofstring) {log.i (str2, num + "\ t"); } initial_memory = Integer.valueof (Arrayofstring[1]). Intvalue () * 1024;//get total system memory, in KB, multiplied by 1024 to byte Loca 
 
    Lbufferedreader.close (); The catch (IOException e) {} return Formatter.formatfilesize (Getbasecontext (), initial_memory);//byte converts to KB or MB, inside The Save size Normalization}/** called when the "activity is" is a. 
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 
    Setcontentview (R.layout.main); 
    TV = (TextView) Findviewbyid (r.id.system_memory); 
  Tv.settext ("Mobile Total Memory:" + this.gettotalmemory () + "," + "available Memory:" + this.getavailmemory ());  } 
}

Successfully read the total memory of the Android phone and the current available memory. Here is just a good point, we can extrapolate, to expand. Of course, we can also read "/proc/cupinfo" to obtain the Android phone CPU parameters, by reading "/proc/stat" file to calculate the CPU usage, here no longer repeat.

The second method: The hand uses the Java reflection mechanism to obtain some information about the cell phone's memory.

The public class Getfreemem extends activity {/** called the ' when ' is the ' The activity ' is a./@Override public VO 
    ID onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    Method _readproclines = null; 
      try {Class procclass; 
      Procclass = Class.forName ("android.os.Process"); 
      Class parametertypes[]= New class[] {string.class, string[].class, long[].class}; 
      _readproclines = Procclass.getmethod ("Readproclines", parametertypes); 
      Object arglist[] = new OBJECT[3]; 
      Final string[] Mmeminfofields = new string[] {"Memtotal:", "Memfree:", "Buffers:", "Cached:"}; 
      long[] mmeminfosizes = new Long[mmeminfofields.length]; 
      Mmeminfosizes[0] = 30; 
      MMEMINFOSIZES[1] =-30; 
      Arglist[0] = new String ("/proc/meminfo"); 
      ARGLIST[1] = Mmeminfofields; 
      ARGLIST[2] = mmeminfosizes; if (_readproclines!=null) {_readproclines.invoke (null, arglist); for (int i=0; i<mmeminfosizes.length; i++) {log.d ("Getfreemem", mmeminfofields[i]+ ":" +mmeminfosizes[i]/10 
        24); 
    A catch (ClassNotFoundException e) {e.printstacktrace ()); 
    catch (SecurityException e) {e.printstacktrace (); 
    catch (IllegalArgumentException e) {e.printstacktrace (); 
    catch (Illegalaccessexception e) {e.printstacktrace (); 
    catch (InvocationTargetException e) {e.printstacktrace (); 
    catch (Nosuchmethodexception e) {e.printstacktrace ();  } 
  } 
}

The above is the information on Android to get memory information collation, do this Android development friends can see.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.