android下如何讀取nand、sd卡cid等其他資訊
阿新 • • 發佈:2019-01-01
某些軟體註冊碼需要繫結SD卡,這時候需要一個唯一標識碼UUID,一般我們會獲取SD卡的CID。如何獲取CID呢,一般有兩種方案:
如上獲取的是nand的唯一標識碼。
1、通過讀取cat /sys/block/mmcblkx/device/cid 來獲取,一般過程是先獲取device/type更加type的型別來確定裝置型別,常見型別mmc,sd,然後再讀取device/cid來獲取裝置唯一標識碼。
例如:
這個是獲取的mmcblk1一般是sdcard的唯一標識碼。private String readDev1() { String str1 = null; Object localOb; try { localOb = new FileReader("/sys/block/mmcblk1/device/type"); localOb = new BufferedReader((Reader) localOb).readLine() .toLowerCase().contentEquals("sd"); if (localOb != null) { str1 = "/sys/block/mmcblk1/device/"; } localOb = new FileReader(str1 + "cid"); // SD Card ID str1 = new BufferedReader((Reader) localOb).readLine(); Log.v(TAG, "cid: " + str1); } catch (Exception e1) { e1.printStackTrace(); } return str1; }
private String readDev0() { String str1 = null; Object localOb; try { localOb = new FileReader("/sys/block/mmcblk0/device/type"); localOb = new BufferedReader((Reader) localOb).readLine() .toLowerCase().contentEquals("mmc"); if (localOb != null) { str1 = "/sys/block/mmcblk0/device/"; } localOb = new FileReader(str1 + "cid"); // nand ID str1 = new BufferedReader((Reader) localOb).readLine(); Log.v(TAG, "nid: " + str1); } catch (Exception e1) { e1.printStackTrace(); } return str1; }
如上獲取的是nand的唯一標識碼。
2、還有一種方法獲取裝置cid,就是使用shell命令
/** * 執行一個shell命令,並返回字串值 * * @param cmd * 命令名稱&引數組成的陣列(例如:{"/system/bin/cat", "/proc/version"}) * @param workdirectory * 命令執行路徑(例如:"system/bin/") * @return 執行結果組成的字串 * @throws IOException */ public static synchronized String run(String[] cmd, String workdirectory) throws IOException { StringBuffer result = new StringBuffer(); try { // 建立作業系統程序(也可以由Runtime.exec()啟動) // Runtime runtime = Runtime.getRuntime(); // Process proc = runtime.exec(cmd); // InputStream inputstream = proc.getInputStream(); ProcessBuilder builder = new ProcessBuilder(cmd); InputStream in = null; // 設定一個路徑(絕對路徑了就不一定需要) if (workdirectory != null) { // 設定工作目錄(同上) builder.directory(new File(workdirectory)); // 合併標準錯誤和標準輸出 builder.redirectErrorStream(true); // 啟動一個新程序 Process process = builder.start(); // 讀取程序標準輸出流 in = process.getInputStream(); byte[] re = new byte[1024]; while (in.read(re) != -1) { result = result.append(new String(re)); } } // 關閉輸入流 if (in != null) { in.close(); } } catch (Exception ex) { ex.printStackTrace(); } return result.toString(); }
然後使用如下命令,其中mxsdhci.o因平臺而已,此種方法對與固定平臺有效。
String[] cmmd = { "/system/bin/cat",
"/sys/devices/platform/mxsdhci.0/mmc_host/mmc0/mmc0:0001/cid" };
String r = run(cmmd, "system/bin/");
裝置的其他資訊獲取可以參照下面這篇博文: