你可以将上面的答案与这个答案结合使用。这样,它在运行API 17+的设备上将更快,因为这种方法比过滤文件要快得多。
private int getNumberOfCores() {
if(Build.VERSION.SDK_INT >= 17) {
return Runtime.getRuntime().availableProcessors()
}
else {
return getNumCoresOldPhones();
}
}
private int getNumCoresOldPhones() {
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
if(Pattern.matches("cpu[0-9]+", pathname.getName())) {
return true;
}
return false;
}
}
try {
File dir = new File("/sys/devices/system/cpu/");
File[] files = dir.listFiles(new CpuFilter());
return files.length;
} catch(Exception e) {
return 1;
}
}
public int availableProcessors ()
在API level 1中添加,返回虚拟机可用的处理器内核数量,至少为1。传统上,这返回当前在线的数量,但许多移动设备可以将未使用的内核脱机以节省电力,因此Android 4.2(Jelly Bean)之后的版本将返回最大可用内核数,如果没有电源或热量限制。
还有一个关于位于/sys/devices/system/cpu/present
文件内核数量的信息。它以以下格式报告可用CPU的数量:
- 0 -> 单个CPU/内核
- 0-1 -> 两个CPU/内核
- 0-3 -> 四个CPU/内核
- 0-7 -> 八个CPU/内核
等等。
另外,请检查Note 3上/sys/devices/system/cpu/possible
文件的内容。
这两个文件都设置了r--r--r--
或者444
的文件权限,所以您应该能够在代码中读取它们而无需root设备。
编辑:发布代码以帮助您。
private void printNumberOfCores() {
printFile("/sys/devices/system/cpu/present");
printFile("/sys/devices/system/cpu/possible");
}
private void printFile(String path) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(path);
if (inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
do {
line = bufferedReader.readLine();
Log.d(path, line);
} while (line != null);
}
} catch (Exception e) {
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
结果如下
D//sys/devices/system/cpu/present﹕ 0-3
D//sys/devices/system/cpu/possible﹕ 0-3
这个测试是在运行BlissPop ROM且搭载Android v5.1.1的OnePlus One上进行的,输出结果符合预期。请在您的三星手机上尝试。