当前位置: 首页 > news >正文

android获取RAM、CPU频率、系统版本、CPU核数

参考链接:
https://www.jianshu.com/p/76d68d13c475
https://github.com/matthewYang92/Themis

获取CPU频率、核数的逻辑,是通过文件操作实现的,Android是基于Linux系统的,所以该方式针对不同的手机都是可靠的操作方式。

RAM:

	public static final int DEVICEINFO_UNKNOWN = -1;/*** Calculates the total RAM of the device through Android API or /proc/meminfo.** @param c - Context object for current running activity.* @return Total RAM that the device has, or DEVICEINFO_UNKNOWN = -1 in the event of an error.*/@TargetApi(Build.VERSION_CODES.JELLY_BEAN)public static long getTotalMemory(Context c) {// 内存是按照1024计算int thundred = 1024;// memInfo.totalMem not supported in pre-Jelly Bean APIs.if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);am.getMemoryInfo(memInfo);if (memInfo != null) {return memInfo.totalMem / (thundred * thundred);} else {return DEVICEINFO_UNKNOWN;}} else {// 低版本不做处理,因此默认返回0return DEVICEINFO_UNKNOWN;}}

CPU频率:

    /*** Method for reading the clock speed of a CPU core on the device. Will read from either* {@code /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq} or {@code /proc/cpuinfo}.** @return Clock speed of a core on the device, or -1 in the event of an error.*/public static ArrayList<Integer> getCPUFreqMHzs() {int maxFreq = DEVICEINFO_UNKNOWN;int curFreq = 0;ArrayList<Integer> arrayList = new ArrayList<Integer>();try {int coreNum = getNumberOfCPUCores();for (int i = 0; i < coreNum; i++) {String filename ="/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq";File cpuInfoMaxFreqFile = new File(filename);if (cpuInfoMaxFreqFile.exists() && cpuInfoMaxFreqFile.canRead()) {byte[] buffer = new byte[128];FileInputStream stream = new FileInputStream(cpuInfoMaxFreqFile);try {stream.read(buffer);int endIndex = 0;//Trim the first number out of the byte buffer.while (Character.isDigit(buffer[endIndex]) && endIndex < buffer.length) {endIndex++;}String str = new String(buffer, 0, endIndex);// 频率是按照1000计算curFreq = Integer.parseInt(str) / 1000;arrayList.add(curFreq);} catch (NumberFormatException e) {} finally {stream.close();}}}if (maxFreq == DEVICEINFO_UNKNOWN && arrayList.size() == 0) {FileInputStream stream = new FileInputStream("/proc/cpuinfo");try {int freqBound = parseFileForValue("cpu MHz", stream);curFreq = freqBound;arrayList.add(curFreq);} finally {stream.close();}}} catch (IOException e) {}return arrayList;}/*** Reads the number of CPU cores from the first available information from* {@code /sys/devices/system/cpu/possible}, {@code /sys/devices/system/cpu/present},* then {@code /sys/devices/system/cpu/}.** @return Number of CPU cores in the phone, or DEVICEINFO_UKNOWN = -1 in the event of an error.*/public static int getNumberOfCPUCores() {if (coreNumber != DEVICEINFO_UNKNOWN) {return coreNumber;}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.coreNumber = 1;return coreNumber;}int cores;try {cores = getCoresFromFileInfo("/sys/devices/system/cpu/present");if (cores == DEVICEINFO_UNKNOWN) {cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length;;}} catch (SecurityException e) {cores = DEVICEINFO_UNKNOWN;} catch (NullPointerException e) {cores = DEVICEINFO_UNKNOWN;}coreNumber = cores;return coreNumber;}/*** Tries to read file contents from the file location to determine the number of cores on device.* @param fileLocation The location of the file with CPU information* @return Number of CPU cores in the phone, or DEVICEINFO_UKNOWN = -1 in the event of an error.*/private static int getCoresFromFileInfo(String fileLocation) {InputStream is = null;try {is = new FileInputStream(fileLocation);BufferedReader buf = new BufferedReader(new InputStreamReader(is));String fileContents = buf.readLine();buf.close();return getCoresFromFileString(fileContents);} catch (IOException e) {return DEVICEINFO_UNKNOWN;} finally {if (is != null) {try {is.close();} catch (IOException e) {// Do nothing.}}}}/*** Converts from a CPU core information format to number of cores.* @param str The CPU core information string, in the format of "0-N"* @return The number of cores represented by this string*/private static int getCoresFromFileString(String str) {if (str == null || !str.matches("0-[\\d]+$")) {return DEVICEINFO_UNKNOWN;}return Integer.valueOf(str.substring(2)) + 1;}private static final FileFilter CPU_FILTER = new FileFilter() {@Overridepublic 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 (!Character.isDigit(path.charAt(i))) {return false;}}return true;}return false;}};/*** Helper method for reading values from system files, using a minimised buffer.** @param textToMatch - Text in the system files to read for.* @param stream      - FileInputStream of the system file being read from.* @return A numerical value following textToMatch in specified the system file.* -1 in the event of a failure.*/private static int parseFileForValue(String textToMatch, FileInputStream stream) {byte[] buffer = new byte[1024];try {int length = stream.read(buffer);for (int i = 0; i < length; i++) {if (buffer[i] == '\n' || i == 0) {if (buffer[i] == '\n') i++;for (int j = i; j < length; j++) {int textIndex = j - i;//Text doesn't match query at some point.if (buffer[j] != textToMatch.charAt(textIndex)) {break;}//Text matches query here.if (textIndex == textToMatch.length() - 1) {return extractValue(buffer, j);}}}}} catch (IOException e) {//Ignore any exceptions and fall through to return unknown value.} catch (NumberFormatException e) {}return DEVICEINFO_UNKNOWN;}/*** Helper method used by {@link #parseFileForValue(String, FileInputStream) parseFileForValue}. Parses* the next available number after the match in the file being read and returns it as an integer.* @param index - The index in the buffer array to begin looking.* @return The next number on that line in the buffer, returned as an int. Returns* DEVICEINFO_UNKNOWN = -1 in the event that no more numbers exist on the same line.*/private static int extractValue(byte[] buffer, int index) {while (index < buffer.length && buffer[index] != '\n') {if (Character.isDigit(buffer[index])) {int start = index;index++;while (index < buffer.length && Character.isDigit(buffer[index])) {index++;}String str = new String(buffer, 0, start, index - start);return Integer.parseInt(str);}index++;}return DEVICEINFO_UNKNOWN;}

系统版本:

String systemVersion = android.os.Build.VERSION.RELEASE;

CPU核数:

    /*** Reads the number of CPU cores from the first available information from* {@code /sys/devices/system/cpu/possible}, {@code /sys/devices/system/cpu/present},* then {@code /sys/devices/system/cpu/}.** @return Number of CPU cores in the phone, or DEVICEINFO_UKNOWN = -1 in the event of an error.*/public static int getNumberOfCPUCores() {if (coreNumber != DEVICEINFO_UNKNOWN) {return coreNumber;}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.coreNumber = 1;return coreNumber;}int cores;try {cores = getCoresFromFileInfo("/sys/devices/system/cpu/present");if (cores == DEVICEINFO_UNKNOWN) {cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length;;}} catch (SecurityException e) {cores = DEVICEINFO_UNKNOWN;} catch (NullPointerException e) {cores = DEVICEINFO_UNKNOWN;}coreNumber = cores;return coreNumber;}

相关文章:

android获取RAM、CPU频率、系统版本、CPU核数

参考链接&#xff1a; https://www.jianshu.com/p/76d68d13c475 https://github.com/matthewYang92/Themis 获取CPU频率、核数的逻辑&#xff0c;是通过文件操作实现的&#xff0c;Android是基于Linux系统的&#xff0c;所以该方式针对不同的手机都是可靠的操作方式。 RAM&am…...

微信小程序python+nodejs+php+springboot+vue 讲座预约系统

讲座预约管理系统的用户是系统最根本使用者&#xff0c;按需要分析系统包括用户&#xff1a;学生、管理员。 管理员通过后台的登录页面&#xff0c;选择管理员权限后进行登录&#xff0c;管理员的权限包括学生信息管理和文章公告管理。讲座公告管理&#xff0c;添加讲座公告信息…...

嵌入式开发笔记:STM32的外设GPIO知识学习

GPIO简介&#xff1a; • GPIO &#xff08; General Purpose Input Output &#xff09;通用输入输出口 • 可配置为 8 种输入输出模式 • 引脚电平&#xff1a; 0V~3.3V &#xff0c;部分引脚可容忍 5V &#xff08;如舵机和驱动直流电机&#xff09; • 输出模式下可控制端口…...

单片机论文参考:2、基于单片机的病床呼叫系统设计

任务要求 设计病床呼叫系统&#xff0c;使用3X8矩阵开关分别模拟医院病房与病床位数&#xff0c;当某开关按下时&#xff0c;系统显示呼叫的病房与病床、呼叫的时间。处理完毕可清除该呼叫显示记录。同时有数个病床呼叫时&#xff0c;可以循环呼叫记录显示。 摘要 病房呼叫系统…...

【C语言】结构体实现位段!位段有何作用?

本篇文章目录 1. 声明位段2. 位段的内存分配3. 位段的跨平台问题4.位段的应用5. 如何解决位段的跨平台问题&#xff1f; 1. 声明位段 位段的声明和结构是类似的&#xff0c;有两个不同&#xff1a; 位段的成员必须是 int、unsigned int 或 char。位段的成员名后边有一个冒号和…...

msvcp140为什么会丢失?msvcp140.dll丢失的解决方法

msvcp140.dll 是一个动态链接库文件&#xff0c;它包含了 C 运行时库的一些函数和类&#xff0c;例如全局对象、异常处理、内存管理、文件操作等。它是 Visual Studio 2015 及以上版本中的一部分&#xff0c;用于支持 C 应用程序的运行。如果 msvcp140.dll 丢失或损坏&#xff…...

Ingress Controller

什么是 Ingress Controller &#xff1f; 在云原生生态中&#xff0c;通常来讲&#xff0c;入口控制器( Ingress Controller )是 Kubernetes 中的一个关键组件&#xff0c;用于管理入口资源对象。 Ingress 资源对象用于定义来自外网的 HTTP 和 HTTPS 规则&#xff0c;以控制进…...

离线安装 K3S

一、前言 简要记录一下离线环境下 K3S 的搭建&#xff0c;版本为 v1.23.17k3s1&#xff0c;使用外部数据库 MySQL 作元数据存储&#xff0c;禁用默认组件&#xff08;coredns、servicelb、traefik、local-storage、metrics-server&#xff09;并使用 Helm 单独安装&#xff08…...

Error系列-常见异常问题解决方案以及系统指令总结

前情提要 作为一名开发&#xff0c;日常工作中会遇到很多报错的情况&#xff0c;希望我的总结可以帮助到小伙伴们~日常工作中也会遇到需要部署项目或者登陆linux系统操作的情况&#xff0c;很多时候需要查找一些命令&#xff0c;于是我决定&#xff0c;要把我日常经常用到的一…...

c 各种例子

1. struct{ int code; float cost; }item,*ptrst; ptrst&item; prtst->code3451 // ptrst->codeitem.code(*ptrst).code 结构与union 的运算符相同&#xff0c;不同的是union 在同一时间内只能存储成员中的一种&#xff0c;其他的成员不真实。 2. c的修饰符声…...

Flowable主要子流程介绍

1. 内嵌子流程 &#xff08;1&#xff09;说明 内嵌子流程又叫嵌入式子流程&#xff0c;它是一个可以包含其它活动、分支、事件&#xff0c;等的活动。我们通常意义上说的子流程通常就是指的内嵌子流程&#xff0c;它表现为将一个流程&#xff08;子流程&#xff09;定…...

通过插件去除Kotlin混淆去除 @Metadata标记

在Kotlin中&#xff0c;Metadata是指描述Kotlin类的元数据。它包含了关于类的属性、函数、注解和其他信息的描述。Metadata的作用主要有以下几个方面&#xff1a; 反射&#xff1a;Metadata可以用于在运行时获取类的信息&#xff0c;包括类的名称、属性、函数等。通过反射&…...

【docker】容器跟宿主机、其他容器通信

说明 容器跟宿主机、其他容器通信的关键在于它们要在同一个网络&#xff0c;或者通过修改路由信息来可以让它们互相之间能够找得到对方的 IP。本文主要介绍让它们在同一个网络的方法。 Docker 自定义网络模式介绍 Docker容器可以通过自定义网络来与宿主机或其他容器进行通信…...

nginx重要配置参数

1、https配置证书 nginx配置https访问_LMD菜鸟先飞的博客-CSDN博客 2、同一个端口代理多个页面 nginx同一个地址端口代理多个页面_同一ip,端口,访问不同页面 nginx_LMD菜鸟先飞的博客-CSDN博客 3、nginx访问压缩数据&#xff0c;加快访问速度 #gzip模块设置gzip on; #开启g…...

Docker 部署 PostgreSQL 服务

拉取最新版本的 PostgreSQL 镜像&#xff1a; $ sudo docker pull postgres:latest在本地预先创建好 data 目录, 用于映射 PostgreSQL 容器内的 /var/lib/postgresql/data 目录。 使用以下命令来运行 PostgreSQL 容器: $ sudo docker run -itd --name postgres -e POSTGRES_…...

【通信误码】python实现-附ChatGPT解析

1.题目 通信误码 时间限制: 1s 空间限制: 32MB 限定语言: 不限 题目描述: 信号传播过程中会出现一些误码,不同的数字表示不同的误码ID, 取值范围为1~65535,用一个数组“记录误码出现的情况。 每个误码出现的次数代表误码频度, 请找出记录中包含频度最高误码的最小子数组长度…...

人与机器只能感知到可以分类的事物?

众所周知&#xff0c;人与机器都能够感知和分类事物。人类拥有感官系统&#xff0c;如视觉、听觉、嗅觉、触觉和味觉&#xff0c;可以通过感知事物的外部特征和属性来进行分类。机器可以通过传感器和算法来感知和分类事物&#xff0c;比如计算机视觉技术可以通过图像和视频数据…...

2023华为杯数学建模竞赛E题

一、前言 颅内出血&#xff08;ICH&#xff09;是由多种原因引起的颅腔内出血性疾病&#xff0c;既包括自发性出血&#xff0c;又包括创伤导致的继发性出血&#xff0c;诊断与治疗涉及神经外科、神经内科、重症医学科、康复科等多个学科&#xff0c;是临床医师面临的重要挑战。…...

AIX360-CEMExplainer: MNIST Example

CEMExplainer: MNIST Example 这一部分屁话有点多&#xff0c;导包没问题的话可以跳过加载MNIST数据集加载经过训练的MNIST模型加载经过训练的卷积自动编码器模型&#xff08;可选&#xff09;初始化CEM解释程序以解释模型预测解释输入实例获得相关否定&#xff08;Pertinent N…...

TouchGFX之自定义控件

在创建应用时&#xff0c;您可能需要TouchGFX中没有包含的控件。在创建应用时&#xff0c;您可能需要TouchGFX中没有包含的控件。但有时此法并不够用&#xff0c;当您需要全面控制帧缓冲时&#xff0c;您需要使用自定义控件法。 TouchGFX Designer目前不支持自定义控件的创建。…...

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…...

零门槛NAS搭建:WinNAS如何让普通电脑秒变私有云?

一、核心优势&#xff1a;专为Windows用户设计的极简NAS WinNAS由深圳耘想存储科技开发&#xff0c;是一款收费低廉但功能全面的Windows NAS工具&#xff0c;主打“无学习成本部署” 。与其他NAS软件相比&#xff0c;其优势在于&#xff1a; 无需硬件改造&#xff1a;将任意W…...

docker详细操作--未完待续

docker介绍 docker官网: Docker&#xff1a;加速容器应用程序开发 harbor官网&#xff1a;Harbor - Harbor 中文 使用docker加速器: Docker镜像极速下载服务 - 毫秒镜像 是什么 Docker 是一种开源的容器化平台&#xff0c;用于将应用程序及其依赖项&#xff08;如库、运行时环…...

中南大学无人机智能体的全面评估!BEDI:用于评估无人机上具身智能体的综合性基准测试

作者&#xff1a;Mingning Guo, Mengwei Wu, Jiarun He, Shaoxian Li, Haifeng Li, Chao Tao单位&#xff1a;中南大学地球科学与信息物理学院论文标题&#xff1a;BEDI: A Comprehensive Benchmark for Evaluating Embodied Agents on UAVs论文链接&#xff1a;https://arxiv.…...

mongodb源码分析session执行handleRequest命令find过程

mongo/transport/service_state_machine.cpp已经分析startSession创建ASIOSession过程&#xff0c;并且验证connection是否超过限制ASIOSession和connection是循环接受客户端命令&#xff0c;把数据流转换成Message&#xff0c;状态转变流程是&#xff1a;State::Created 》 St…...

数据链路层的主要功能是什么

数据链路层&#xff08;OSI模型第2层&#xff09;的核心功能是在相邻网络节点&#xff08;如交换机、主机&#xff09;间提供可靠的数据帧传输服务&#xff0c;主要职责包括&#xff1a; &#x1f511; 核心功能详解&#xff1a; 帧封装与解封装 封装&#xff1a; 将网络层下发…...

蓝桥杯 冶炼金属

原题目链接 &#x1f527; 冶炼金属转换率推测题解 &#x1f4dc; 原题描述 小蓝有一个神奇的炉子用于将普通金属 O O O 冶炼成为一种特殊金属 X X X。这个炉子有一个属性叫转换率 V V V&#xff0c;是一个正整数&#xff0c;表示每 V V V 个普通金属 O O O 可以冶炼出 …...

HarmonyOS运动开发:如何用mpchart绘制运动配速图表

##鸿蒙核心技术##运动开发##Sensor Service Kit&#xff08;传感器服务&#xff09;# 前言 在运动类应用中&#xff0c;运动数据的可视化是提升用户体验的重要环节。通过直观的图表展示运动过程中的关键数据&#xff0c;如配速、距离、卡路里消耗等&#xff0c;用户可以更清晰…...

VM虚拟机网络配置(ubuntu24桥接模式):配置静态IP

编辑-虚拟网络编辑器-更改设置 选择桥接模式&#xff0c;然后找到相应的网卡&#xff08;可以查看自己本机的网络连接&#xff09; windows连接的网络点击查看属性 编辑虚拟机设置更改网络配置&#xff0c;选择刚才配置的桥接模式 静态ip设置&#xff1a; 我用的ubuntu24桌…...

鸿蒙HarmonyOS 5军旗小游戏实现指南

1. 项目概述 本军旗小游戏基于鸿蒙HarmonyOS 5开发&#xff0c;采用DevEco Studio实现&#xff0c;包含完整的游戏逻辑和UI界面。 2. 项目结构 /src/main/java/com/example/militarychess/├── MainAbilitySlice.java // 主界面├── GameView.java // 游戏核…...