因為Android本質上是linux系統,所以關系硬件相關的信息實際上是用文件表示的
CPU相關信息放在 /sys/devices/system/cpu/
這個路徑下,
要知道cpu的核數只需要查看這個路徑中的文件即可
如果CPU是雙核的,則 /sys/devices/system/cpu/
路徑下有兩個子文件夾cpu0
和cpu1
如果CPU是四核的,則 /sys/devices/system/cpu/
路徑下有四個子文件夾cpu0
和cpu1
和cpu2
和cpu3
以此類推
用JAVA代碼來獲取CPU核數:
這個是抄來的
public static int getNumberOfCPUCores() {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
// Gingerbread doesn't support giving a single application access to both cores, but a
// handful of devices (Atrix 4G and Droid X2 for example) were released with a dual-core
// chipset and Gingerbread; that can let an app in the background run without impacting
// the foreground application. But for our purposes, it makes them single core.
return 1; //上面的意思就是2.3以前不支持多核,有些特殊的設備有雙核...不考慮,就當單核!!
}
int cores;
try {
cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length;
} catch (SecurityException e) {
cores = DEVICEINFO_UNKNOWN; //這個常量得自己約定
} catch (NullPointerException e) {
cores = DEVICEINFO_UNKNOWN;
}
return cores;
}
private static final FileFilter CPU_FILTER = new FileFilter() {
@Override
public boolean accept(File pathname) {
String path = pathname.getName();
//regex is slow, so checking char by char.
if (path.startsWith("cpu")) {
for (int i = 3; i < path.length(); i++) {
if (path.charAt(i) < '0' || path.charAt(i) > '9') {
return false;
}
}
return true;
}
return false;
}
};