編輯:關於 Android 程式設計
做診斷頁、客服回報或相容性統計時,常需要把裝置資訊收集起來。Android 上的資料來源主要分成兩類:一類是 Linux 的 /proc 虛擬檔案系統,另一類是 framework 提供的 API。
CPU 型號等資訊可讀 /proc/cpuinfo,各核心的活動統計則在 /proc/stat(用來計算使用率);記憶體資訊在 /proc/meminfo;系統版本在 /proc/version。
public class CpuManager {
/** 取得 CPU 最高頻率(單位 KHz) */
public static String getMaxCpuFreq() {
String result = "";
try {
String[] args = {
"/system/bin/cat",
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"
};
ProcessBuilder cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[24];
while (in.read(re) != -1) {
result = result + new String(re);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
result = "N/A";
}
return result.trim();
}
/** 取得 CPU 最低頻率(單位 KHz) */
public static String getMinCpuFreq() {
String result = "";
try {
String[] args = {
"/system/bin/cat",
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"
};
ProcessBuilder cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[24];
while (in.read(re) != -1) {
result = result + new String(re);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
result = "N/A";
}
return result.trim();
}
/** 即時取得 CPU 目前頻率(單位 KHz) */
public static String getCurCpuFreq() {
String result = "N/A";
try {
FileReader fr = new FileReader(
"/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
BufferedReader br = new BufferedReader(fr);
result = br.readLine().trim();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/** 取得 CPU 名稱 */
public static String getCpuName() {
try {
FileReader fr = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
String[] array = text.split(":\\s+", 2);
return array[1];
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
提醒:讀取 cpufreq 節點需要檔案權限,部分機型在較新 Android 版本上已對一般應用關閉此節點,此時會得到 "N/A"。另外 byte[24] 搭配字串相加的寫法效率不佳,實務上建議直接用 BufferedReader.readLine() 讀一行即可。
public void getTotalMemory() {
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) {
// 忽略
}
}
輸出中會包含 MemTotal、MemFree、Buffers、Cached 等欄位,自行解析需要的部分即可。
public long[] getRomMemroy() {
long[] romInfo = new long[2];
// 總容量
romInfo[0] = getTotalInternalMemorySize();
// 可用容量
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
romInfo[1] = blockSize * availableBlocks;
getVersion();
return romInfo;
}
public long getTotalInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}
public long[] getSDCardMemory() {
long[] sdCardInfo = new long[2];
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File sdcardDir = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(sdcardDir.getPath());
long bSize = sf.getBlockSize();
long bCount = sf.getBlockCount();
long availBlocks = sf.getAvailableBlocks();
sdCardInfo[0] = bSize * bCount; // 總大小
sdCardInfo[1] = bSize * availBlocks; // 可用大小
}
return sdCardInfo;
}
記得先判斷掛載狀態,未掛載時 getBlockCount() 的值不具意義。若要讀取任意外部目錄,Android 6.0 以上還需要動態申請儲存權限。
private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra("level", 0);
int scale = intent.getIntExtra("scale", 100);
int batteryPct = (int) (level * 100 / (float) scale);
// batteryPct 即為當前電量百分比
}
};
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
除了 level,這個廣播還帶有 temperature、voltage、status、health 等欄位,做電池診斷時值得一併收集。別忘了在 onDestroy() 中 unregisterReceiver(),否則會造成記憶體洩漏。
public String[] getVersion() {
String[] version = {"null", "null", "null", "null"};
String str1 = "/proc/version";
try {
FileReader localFileReader = new FileReader(str1);
BufferedReader localBufferedReader =
new BufferedReader(localFileReader, 8192);
String str2 = localBufferedReader.readLine();
String[] arrayOfString = str2.split("\\s+");
version[0] = arrayOfString[2]; // 核心版本
localBufferedReader.close();
} catch (IOException e) {
// 忽略
}
version[1] = Build.VERSION.RELEASE; // 作業系統版本
version[2] = Build.MODEL; // 機型
version[3] = Build.DISPLAY; // 系統版本(客製名稱)
return version;
}
public String[] getOtherInfo() {
String[] other = {"null", "null"};
WifiManager wifiManager =
(WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo.getMacAddress() != null) {
other[0] = wifiInfo.getMacAddress();
} else {
other[0] = "Fail";
}
other[1] = getTimes();
return other;
}
private String getTimes() {
long ut = SystemClock.elapsedRealtime() / 1000;
if (ut == 0) {
ut = 1;
}
int m = (int) ((ut / 60) % 60);
int h = (int) ((ut / 3600));
return h + " " + mContext.getString(R.string.info_times_hour)
+ m + " " + mContext.getString(R.string.info_times_minute);
}
這裡有兩個重要變更要注意:Android 6.0 之後,一般應用透過 WifiInfo.getMacAddress() 只能拿到固定值 02:00:00:00:00:00,無法取得真實硬體位址。若目的是裝置唯一識別,請改用其他方案並留意隱私政策規範。
另外 SystemClock.elapsedRealtime() 回傳的是開機以來的毫秒數(含休眠時間),不含手動改時間的影響,因此拿來算「已開機多久」是準確的;若要用 uptimeMillis() 則不包含深度休眠期間。
這一類資訊屬於敏感資料,實務上有幾點要留意:一是只在必要時收集,並在隱私政策中說明用途;二是所有 /proc 讀取都要有例外處理,因為不同廠商、不同版本的節點存在性差異很大;三是若要上傳,建議加上版本號與收集時間,後續分析才不會混淆。
Android 開發:如何進行真機除錯?
一般來說,真機除錯是最快的方式,因此建議大家直接使用真機來除錯。具體步驟可參考下圖:
我眼中的 Window:建立、新增、移除與更新的完整機制
做 Android 開發,跟我們打交道最多的莫過於 Activity,因為我們不斷地與畫面互動。而 Activity 內部所有跟界面有關的操作,其實都是由 Window
Android 開發學習之路:網路編程之 XML 與 JSON 解析
網路資料透過 HTTP 以 GET 或 POST 傳輸,但資料本身不可能雜亂無章——傳輸雙方必須約定好格式與結構,否則無從解析起。最常見的兩種就是 XML 與 JSON。
Android Service 服務詳解:生命週期、兩種啟動方式與遠程 AIDL
Service 作為 Android 四大元件之一,自然是重點。本文說明服務的生命週期、兩種啟動方式(以及混合啟動),最後示範如何跨應用呼叫遠程服務。 一、服務的正常啟動