您可以将上述答案与此答案结合使用。这样它会在运行 API 17+ 的设备上执行得更快,因为这种方法比过滤掉文件要快得多。
private int getNumberOfCores() {
if(Build.VERSION.SDK_INT >= 17) {
return Runtime.getRuntime().availableProcessors()
}
else {
// Use saurabh64's answer
return getNumCoresOldPhones();
}
}
/**
* Gets the number of cores available in this device, across all processors.
* Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
* @return The number of cores, or 1 if failed to get result
*/
private int getNumCoresOldPhones() {
//Private Class to display only CPU devices in the directory listing
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
//Check if filename is "cpu", followed by a single digit number
if(Pattern.matches("cpu[0-9]+", pathname.getName())) {
return true;
}
return false;
}
}
try {
//Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
//Filter to only list the devices we care about
File[] files = dir.listFiles(new CpuFilter());
//Return the number of cores (virtual CPU devices)
return files.length;
} catch(Exception e) {
//Default to return 1 core
return 1;
}
}
public int availableProcessors ()
在 API 级别 1 中添加 返回可用的处理器内核数
到 VM,至少 1。传统上这返回数字
目前在线,但许多移动设备都可以使用未使用的
核心离线以节省电力,因此发布比 Android 4.2 (Jelly) 更新的版本
Bean) 返回可以使用的最大内核数
如果没有功率或热量限制。
还有关于位于的文件中的核心数量的信息
/sys/devices/system/cpu/present 它以以下格式报告可用 CPU 的数量:
- 0 -> 单 CPU/内核
- 0-1 -> 两个 CPU/内核
- 0-3 -> 四个 CPU/内核
- 0-7 -> 八个 CPU/内核
等等
另外,请检查注释 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 上运行的,它可以正常打印。请尝试使用您的三星