当前位置: 首页 > 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目前不支持自定义控件的创建。…...

centos 7 部署awstats 网站访问检测

一、基础环境准备&#xff08;两种安装方式都要做&#xff09; bash # 安装必要依赖 yum install -y httpd perl mod_perl perl-Time-HiRes perl-DateTime systemctl enable httpd # 设置 Apache 开机自启 systemctl start httpd # 启动 Apache二、安装 AWStats&#xff0…...

《从零掌握MIPI CSI-2: 协议精解与FPGA摄像头开发实战》-- CSI-2 协议详细解析 (一)

CSI-2 协议详细解析 (一&#xff09; 1. CSI-2层定义&#xff08;CSI-2 Layer Definitions&#xff09; 分层结构 &#xff1a;CSI-2协议分为6层&#xff1a; 物理层&#xff08;PHY Layer&#xff09; &#xff1a; 定义电气特性、时钟机制和传输介质&#xff08;导线&#…...

LeetCode - 394. 字符串解码

题目 394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; 思路 使用两个栈&#xff1a;一个存储重复次数&#xff0c;一个存储字符串 遍历输入字符串&#xff1a; 数字处理&#xff1a;遇到数字时&#xff0c;累积计算重复次数左括号处理&#xff1a;保存当前状态&a…...

Objective-C常用命名规范总结

【OC】常用命名规范总结 文章目录 【OC】常用命名规范总结1.类名&#xff08;Class Name)2.协议名&#xff08;Protocol Name)3.方法名&#xff08;Method Name)4.属性名&#xff08;Property Name&#xff09;5.局部变量/实例变量&#xff08;Local / Instance Variables&…...

苍穹外卖--缓存菜品

1.问题说明 用户端小程序展示的菜品数据都是通过查询数据库获得&#xff0c;如果用户端访问量比较大&#xff0c;数据库访问压力随之增大 2.实现思路 通过Redis来缓存菜品数据&#xff0c;减少数据库查询操作。 缓存逻辑分析&#xff1a; ①每个分类下的菜品保持一份缓存数据…...

自然语言处理——Transformer

自然语言处理——Transformer 自注意力机制多头注意力机制Transformer 虽然循环神经网络可以对具有序列特性的数据非常有效&#xff0c;它能挖掘数据中的时序信息以及语义信息&#xff0c;但是它有一个很大的缺陷——很难并行化。 我们可以考虑用CNN来替代RNN&#xff0c;但是…...

3-11单元格区域边界定位(End属性)学习笔记

返回一个Range 对象&#xff0c;只读。该对象代表包含源区域的区域上端下端左端右端的最后一个单元格。等同于按键 End 向上键(End(xlUp))、End向下键(End(xlDown))、End向左键(End(xlToLeft)End向右键(End(xlToRight)) 注意&#xff1a;它移动的位置必须是相连的有内容的单元格…...

DingDing机器人群消息推送

文章目录 1 新建机器人2 API文档说明3 代码编写 1 新建机器人 点击群设置 下滑到群管理的机器人&#xff0c;点击进入 添加机器人 选择自定义Webhook服务 点击添加 设置安全设置&#xff0c;详见说明文档 成功后&#xff0c;记录Webhook 2 API文档说明 点击设置说明 查看自…...

Windows安装Miniconda

一、下载 https://www.anaconda.com/download/success 二、安装 三、配置镜像源 Anaconda/Miniconda pip 配置清华镜像源_anaconda配置清华源-CSDN博客 四、常用操作命令 Anaconda/Miniconda 基本操作命令_miniconda创建环境命令-CSDN博客...

从 GreenPlum 到镜舟数据库:杭银消费金融湖仓一体转型实践

作者&#xff1a;吴岐诗&#xff0c;杭银消费金融大数据应用开发工程师 本文整理自杭银消费金融大数据应用开发工程师在StarRocks Summit Asia 2024的分享 引言&#xff1a;融合数据湖与数仓的创新之路 在数字金融时代&#xff0c;数据已成为金融机构的核心竞争力。杭银消费金…...