Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 取得手機資訊:從 /proc 到自製指令解析器

編輯:關於 Android 程式設計

Android 底層是 Linux,很多系統資訊都放在 /proc 底下,以純文字格式保存,用 IO 流讀起來就能拿到。例如:

cat /proc/cpuinfo   # CPU 資訊
cat /proc/meminfo   # 記憶體資訊
cat /proc/version   # 核心與 GCC 版本

這些都很簡單。但並不是所有內容都以純文字形式存在,磁碟資訊就是例子。與其為每一項都寫一套解析,不如做一個通用的指令解析器,把「執行指令、收集輸出」這件事統一處理。

指令解析器

用 ProcessBuilder 執行指令,把 stdout 整包讀成字串回傳:

public class CMDExecutor {
    /** @param cmd 指令與參數 @param workdir 執行指令時所在目錄(等同下指令後 pwd 看到的) */
    public synchronized String run(String[] cmd, String workdir) {
        String result = "";
        InputStream is = null;
        try {
            ProcessBuilder builder = new ProcessBuilder(cmd);
            if (!TextUtils.isEmpty(workdir)) {
                builder.directory(new File(workdir));
            }
            builder.redirectErrorStream();          // 把 stderr 併到 stdout
            Process process = builder.start();
            is = process.getInputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = is.read(buf)) != -1) {
                result += new String(buf, 0, len);
            }
        } catch (Exception e) {
            return null;
        } finally {
            if (is != null) {
                try { is.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        }
        return result;
    }
}

取得手機資訊的工具類

public class GetPhoneInfoUtil {

    /** 核心版本、GCC 版本等 */
    public String fetch_version_info() {
        CMDExecutor cmdexe = new CMDExecutor();
        String[] args = { "/system/bin/cat", "/proc/version" };
        return cmdexe.run(args, "system/bin/");   // 已指定目錄,args 也可寫相對路徑 "cat"
    }

    /** CPU 資訊 */
    public String fetch_cpu_info() {
        CMDExecutor cmdexe = new CMDExecutor();
        String[] args = { "/system/bin/cat", "/proc/cpuinfo" };
        return cmdexe.run(args, "/system/bin/");
    }

    /** 電信資訊,需加權限 android.permission.READ_PHONE_STATE */
    public String fetch_tel_status(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int mcc = context.getResources().getConfiguration().mcc;
        int mnc = context.getResources().getConfiguration().mnc;
        String str = "DeviceId(IMEI) = " + tm.getDeviceId() + "\n";
        str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + "\n";
        str += "IMSI MCC (Mobile Country Code): " + mcc + "\n";
        str += "IMSI MNC (Mobile Network Code): " + mnc + "\n";
        return str;
    }

    /** 網路組態 */
    public static String fetch_netcfg_info() {
        return new CMDExecutor().run(new String[] { "/system/bin/netcfg" }, "/system/bin/");
    }

    /** 磁碟資訊 */
    public static String fetch_disk_info() {
        return new CMDExecutor().run(new String[] { "/system/bin/df" }, "/system/bin/");
    }

    /** 螢幕資訊 */
    public String getDisplayMetrics(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        String str = "";
        str += "The absolute width: " + dm.widthPixels + "pixels \n";
        str += "The absolute height: " + dm.heightPixels + "pixels \n";
        str += "The logical density of the display: " + dm.density + " \n";
        str += "X dimension: " + dm.xdpi + "pixels per inch \n";
        str += "Y dimension: " + dm.ydpi + "pixels per inch \n";
        return str;
    }
}

JVM 系統屬性

另外,System.getProperty() 也能拿到一些 Java 層的屬性,例如 java.vendor.url、java.class.path、os.name、os.version、user.home 等,適合成為診斷資訊的一部分一起呈現。

幾個實務上的提醒

  • 指令路徑在不同 ROM 上不一定相同,/system/bin 之外也可能在 /system/xbin。寫死絕對路徑前最好先確認,或改用相對指令名稱讓系統去 PATH 找。
  • result += new String(...) 的字串串接,在輸出量大時會產生大量暫存物件,建議改用 StringBuilder。
  • IMEI 這類敏感識別碼在 Android 10 之後已對一般 App 關閉,請改用官方提供的替代 API,不要繞道 /proc 去取。
  • 讀取 /proc 的部分內容在不同 Android 版本與 SELinux 政策下可能被限制,上線前務必在目標機型實測。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved