Android 系统信息的获取

Android 系统信息的获取

一、内存(ram):

1、android 的内存大小信息存放在系统的 /proc/meminfo 文件里面,通过adb shell 进入 手机目录后,使用 cat /proc/meminfo 可以显示这些信息:

[email protected]:/ # cat /proc/meminfo
MemTotal:        1863064 kB
MemFree:          109396 kB
Buffers:           30892 kB
Cached:           835468 kB
SwapCached:            0 kB
Active:           855868 kB
Inactive:         593304 kB
Active(anon):     424552 kB
Inactive(anon):   162992 kB
Active(file):     431316 kB
Inactive(file):   430312 kB
Unevictable:        2268 kB
Mlocked:               0 kB
HighTotal:       1458172 kB
HighFree:          35356 kB
LowTotal:         404892 kB
LowFree:           74040 kB
SwapTotal:        419428 kB
SwapFree:         412148 kB
Dirty:                60 kB
Writeback:             0 kB
AnonPages:        585116 kB
Mapped:           272388 kB
Shmem:              2460 kB
Slab:              52480 kB
SReclaimable:      23556 kB
SUnreclaim:        28924 kB
KernelStack:       14736 kB
PageTables:        35532 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     1350960 kB
Committed_AS:   82837660 kB
VmallocTotal:     409600 kB
VmallocUsed:      181572 kB
VmallocIoRemap:   172600 kB
VmallocAlloc:       8376 kB
VmallocMap:            0 kB
VmallocUserMap:        0 kB
VmallocVpage:       4888 kB
VmallocChunk:      69636 kB
KGSL_ALLOC:        34340 kB
ION_ALLOC:        105376 kB
Kmalloc:            8112 kB
DMA ALLOC:           352 kB
CachedUnmapped:   578420 kB
KgslUnmapped:      19528 kB
Ftrace:            32768 kB

2、在代码中可以通过读取 /proc/meminfo 文件来获取相应的信息:

    public void getTotalRamMemory() {
        String str1 = "/proc/meminfo";
        String str2 = "";
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            while ((str2 = localBufferedReader.readLine()) != null) {
                Log.i(TAG, "---" + str2);
            }
        } catch (IOException e) {
        }
    }

3、也可以通过 ActivityManager.MemoryInfo 来获取相应的信息:

    public long getAvailRamMemory(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi.availMem;
    } 

二、机身容量(Rom大小)

1、android 机身容量,通过adb shell 进入 手机目录后,使用 df 命令可以显示手机挂载分区详细信息:

[email protected]:/ # df
Filesystem               Size     Used     Free   Blksize
/dev                   909.7M    68.0K   909.6M   4096
/sys/fs/cgroup         909.7M    12.0K   909.7M   4096
/mnt/asec              909.7M     0.0K   909.7M   4096
/mnt/obb               909.7M     0.0K   909.7M   4096
/system               1763.8M  1589.9M   174.0M   4096
/data                 26206.2M  3082.8M  23123.4M   4096
/cache                 629.9M    10.5M   619.4M   4096
/devlog                 19.7M    15.8M     3.9M   4096
/carrier                24.6M     4.0M    20.6M   4096
/firmware/mdm           86.0M    69.1M    16.8M   16384
/data/qcks              20.0M     9.0M    11.0M   4096
/data/efs               20.0M     0.0K    20.0M   4096
/firmware/q6           199.8M     6.4M   193.3M   4096
/data/secure/data      909.7M     0.0K   909.7M   4096
/mnt/shell/emulated   26106.2M  3082.8M  23023.4M   4096
/sqlite_stmt_journals   512.0K     0.0K   512.0K   4096

2、在代码中可以通过 df  命令来显示机身容量,这个方法也适用与获取sdCard的大小:

    /**
     * get "/data" block available size.
     *
     * @return available size(kB).
     */
    public static long getDataAvailable() {
        // exec cmd "df" & get column as: Filesystem Size Used Free Blksize;
        // the 3th column of /data is dataFreeSize.
        String dataFreeSizeDetailInfo = getDeviceSystemInfo("df", "/data ", 3)
                .trim();
        // remove the last char of the dataFreeSizeDetailInfo
        String dataFreeSizeShotInfo = dataFreeSizeDetailInfo.substring(0,
                dataFreeSizeDetailInfo.length() - 1);
        float dataFreeSize = Float.parseFloat(dataFreeSizeShotInfo);
        float dataFreeKB = dataFreeSize;
        if (dataFreeSizeDetailInfo.endsWith("G")// GB to kB
                || dataFreeSizeDetailInfo.endsWith("g")) {
            dataFreeKB = dataFreeSize * (1024 * 1024);
        } else if (dataFreeSizeDetailInfo.endsWith("M")// MB to kB
                || dataFreeSizeDetailInfo.endsWith("m")) {
            dataFreeKB = dataFreeSize * 1024;
        } else {// kB to kB
        }
        return (long) dataFreeKB;
    }

    /**
     * get device system info by executing shell command.
     *
     * @param cmd
     *            command to execute by using device shell.
     * @param target
     *            target line or some special line that contain the target
     *            string ,such as "/data"
     * @param column
     *            ={0,1,2,3,...}
     * @return
     */
    public static String getDeviceSystemInfo(String cmd, String target,
            int column) {
        String result = "";
        result = RootCmd.execShellCmd(cmd);
        String[] strs = result.split("\n");
        String info = "-1";
        for (String str : strs) {
            if (str.startsWith(target) && str.contains(target)) {

                Pattern p = Pattern.compile("\\s+");
                Matcher m = p.matcher(str);
                str = m.replaceAll(" ");

                String[] subStr = str.split(" ");
                if (subStr.length < column) {
                    return null;
                }
                String columnInfo = subStr[column];
                info = columnInfo;
            }
        }
        return info;
    }

3、也可以通过 StatFs 来获取机身容量:

    /**
     *
     * 获得机身内存大小
     *
     * @return
     */
    public long getRomTotalSize() {
        File path = Environment.getDataDirectory();
        StatFs statFs = new StatFs(path.getPath());
        long blockSize = statFs.getBlockSizeLong();
        long tatalBlocks = statFs.getBlockCountLong();
        return blockSize * tatalBlocks;
    }

    /**
     * 获得机身可用内存
     *
     * @return
     */
    private long getRomAvailableSize() {
        File path = Environment.getDataDirectory();
        StatFs statFs = new StatFs(path.getPath());
        long blockSize = statFs.getBlockSizeLong();
        long availableBlocks = statFs.getAvailableBlocksLong();
        return blockSize * availableBlocks;
    }

三、sdCard大小

    /**
     *
     * 获得sd卡总共容量
     *
     * @return
     */
    public long getSDTotalSize() {
        /* 获取存储卡路径 */
        File sdcardDir = Environment.getExternalStorageDirectory();
        /* StatFs 看文件体系空间应用景象 */
        StatFs statFs = new StatFs(sdcardDir.getPath());
        long blockSize = statFs.getBlockSizeLong();
        long totalSize = statFs.getBlockCountLong();
        return blockSize * totalSize;
    }

    /**
     *
     * 获得sd卡残剩容量,即可以大小
     *
     * @return
     */
    public long getSdAvaliableSize() {
        File path = Environment.getExternalStorageDirectory();
        StatFs statFs = new StatFs(path.getPath());
        long blockSize = statFs.getBlockSizeLong();
        long availableBlocks = statFs.getAvailableBlocksLong();
        return blockSize * availableBlocks;
    }

四、取得的rom容量和sdcard容量时,常常需要将数据格式化,转换成KB,MB,GB,下面是一个格式化数据的方法: 保留两位小数。

    /**
     * convert size to KB or MB or GB
     *
     * @param size
     * @return
     */
    protected String formatSize(long originSize) {
        String suffix = null;
        float fSize = 0;

        if (originSize >= 1024) {
            suffix = "KB";
            fSize = originSize / 1024;
            if (fSize >= 1024) {
                suffix = "MB";
                fSize /= 1024;
            }
            if (fSize >= 1024) {
                suffix = "GB";
                fSize /= 1024;
            }
        } else {
            fSize = originSize;
        }
        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");
        StringBuilder resultBuffer = new StringBuilder(df.format(fSize));
        if (suffix != null)
            resultBuffer.append(suffix);
        return resultBuffer.toString();
    }

五、CPU信息

1、通过adb shell 进入 手机目录后,使用 cat /proc/cpuinfo 可以显示 CPU 详细信息,/proc/cpuinfo文件中第一行是CPU的型号,第二行是CPU的频率

2、在代码中可以通过读取 /proc/cpuinfo 文件来获取CPU相应的信息:

    /**
     * get CPU info
     *
     * @return
     */
    private String getCPUInfo() {
        StringBuffer sb = new StringBuffer();
        sb.append("abi: ").append(Build.CPU_ABI).append("\n");
        if (new File("/proc/cpuinfo").exists()) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(new File(
                        "/proc/cpuinfo")));
                String aLine;
                while ((aLine = br.readLine()) != null) {
                    sb.append(aLine + "\n");
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

六、系统的版本信息:

    /**
     * get system version
     *
     * @return
     */
    public String[] getVersion() {
        String[] version = { "null", "null", "null", "null" };
        String str1 = "/proc/version";
        String str2;
        String[] arrayOfString;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            version[0] = arrayOfString[2];// KernelVersion
            localBufferedReader.close();
        } catch (IOException e) {
        }
        version[1] = Build.VERSION.RELEASE;// firmware version
        version[2] = Build.MODEL;// model
        version[3] = Build.DISPLAY;// system version
        return version;
    }

七、MAC地址:

    /**
     *
     * @return
     */
    public String getMacInfo(Context context) {
        String macInfo;
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo.getMacAddress() != null) {
            macInfo = wifiInfo.getMacAddress();
        } else {
            macInfo = "Fail";
        }
        return macInfo;
    }

八、电池电量:

    /**
     * register battery broadcast receiver
     *
     * @param context
     */
    public void registerBatteryReceiver(Context context) {
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        context.registerReceiver(batteryReceiver, filter, null, null);
    }

    /**
     * unregister battery broadcast receiver
     *
     * @param context
     */
    public void unregisterBatteryReceiver(Context context) {
        context.unregisterReceiver(batteryReceiver);
    }

    private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int level = intent.getIntExtra("level", 0);
            // level加%就是当前电量了
            System.out.print("Current battery level:" + level);
        }
    };

九、开机时间:

    /**
     *
     * @return
     */
    private String getStartTimes(Context context) {
        long ut = SystemClock.elapsedRealtime() / 1000;
        if (ut == 0) {
            ut = 1;
        }
        int m = (int) ((ut / 60) % 60);
        int h = (int) ((ut / 3600));
        return h + " hours," + m + " minutes.";
    }
时间: 2024-10-02 00:29:37

Android 系统信息的获取的相关文章

Android群英传笔记——第九章:Android系统信息和安全机制

Android群英传笔记--第九章:Android系统信息和安全机制 本书也正式的进入尾声了,在android的世界了,不同的软件,硬件信息就像一个国家的经济水平,军事水平,不同的配置参数,代表着一个android帝国的强弱,所以厂商喜欢打配置战,本节就要是讲 Android系统信息的获取 PackageManager的使用 ActivityManager的使用 Android安全机制 一. Android系统信息的获取 由于android手机的开源性,手机的配置各种各样,那些优化大师之类的东西

Android -- 系统信息(内存、cpu、sd卡、电量、版本)获取

内存(ram)                                                                              android的总内存大小信息存放在系统的/proc/meminfo文件里面,可以通过读取这个文件来获取这些信息: public void getTotalMemory() { String str1 = "/proc/meminfo"; String str2=""; try { FileRead

Android群英传知识点回顾——第九章:Android系统信息与安全机制

9.1 Android系统信息获取 9.1.1 android.os.Build 9.1.2 SystemProperty 9.1.3 Android系统信息实例 9.2 Android Apk应用信息获取之PackageManager 9.2.1 PackageManager 9.3 Android Apk应用信息获取之ActivityManager 9.4 解析Packages.xml获取系统信息 9.5 Android安全机制 9.5.1 Android安全机制简介 9.5.2 Andro

Android手机如何获取power_profile.xml文件

最近在做关于能耗方面的测试,看了一个月时间的论文,终于找到了一些新的思路,但是一个问题出现了,以至于 工作无法再进行下去. 在Android手机中,对于手机中的每个部件(cpu.led.gps.3g等等)运行时对应的能耗值都放power_profile.xml 文件中,而且系统的 设置-->电池-->使用情况中,统计的能耗的使用情况也是以power_profile.xml的value作为基础参数 的.Android手机如何获取power_profile.xml文件呢?接下来我们会详细介绍该问题

android从网络获取图片

http://blog.csdn.net/wangjinyu501/article/details/8219317 http://www.cnblogs.com/JerryWang1991/archive/2012/03/09/2388312.html http://blog.csdn.net/liuhe688/article/details/6532519 http://blog.csdn.net/abc5382334/article/details/17097633 http://www.t

Android调用gallery获取图片

从gallery中获取图片 步骤: 步骤一: // 激活系统图库应用,选择一张图片 Intent intent = new Intent(); // 活动操作:选择一个项目从数据,返回被选中 intent.setAction(Intent.ACTION_PICK); // 设置意图的类型 intent.setType("image/*"); // 设置开启意图 // 设置的是有返回值的意图开启需要重写onActivityResult startActivityForResult(int

Android中StatFs获取系统/sdcard存储(剩余空间)大小

package com.orgcent.util; import java.io.File; import android.os.Environment; import android.os.StatFs; public class MemoryStatus { static final int ERROR = -1; /** * 外部存储是否可用 * @return */ static public boolean externalMemoryAvailable() { return andr

Android的GPS获取方法

Android的GPS获取方法 其实这是一个伪命题:因为我不是要说android的gps获取实现,或者说底层具体实现:而是我直接使用了百度地图的sdk,在其中直接获取到gps信息,以前有做过这个功能,今天就直接将demo介绍一下以利大家. 第一步:获取sdk 在百度地图的开发者官网上直接就可以下载到线程的demo:当然功能相对是齐全的,基本解决需要地图的各种功能了.http://developer.baidu.com/map/index.php?title=androidsdk 第二步,获取ke

android 下动态获取控件的id

有时候我们需要动态的取得一个一个控件的id,然后进行操作,经过在网上查找,找到了一下方法getResources().getIdentifier("textView01", "id", "cn.xxx.xxx"); 第一个参数为ID名,第二个为资源属性是ID或者是Drawable,第三个为包名. 以下是从网上找到资料:主要由两种方法,个人建议第二种. 1. 不把图片放在res/drawable下,而是存放在src某个package中(如:com.