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

Python中match...case的用法

在C语言中有switch...case语句&#xff0c;Pthon3.10之前应该是没有类似语法&#xff0c;从Python3.10开始引入match...case与switch分支语句用法类似&#xff0c;但有细微差别&#xff0c;总结如下&#xff1a; 1.语法 肉眼可见的是关键词从switch变成了match&#xff0c;同…...

深度学习自学笔记二:逻辑回归和梯度下降法

目录 一、逻辑回归 二、逻辑回归的代价函数 三、梯度下降法 一、逻辑回归 逻辑回归是一种常用的二分类算法&#xff0c;用于将输入数据映射到一个概率输出&#xff0c;表示为属于某个类别的概率。它基于线性回归模型&#xff0c;并使用了sigmoid函数作为激活函数。 假设我们…...

【Element】通知 Notification

ElementUI 弹出通知 created() {const h this.$createElementconst that thisthis.$notify({onClose: function () {that.do()},type: warning,duration: 5000, // 5秒后隐藏offset: 0, // 距离顶部dangerouslyUseHTMLString: false, showClose: false,customClass: notify-…...

vue+express、gitee pm2部署轻量服务器(20230923)

一、代码配置 前后端接口都保持 127.0.0.1:3000 vue 项目 创建文件 pm2.config.cjs module.exports {apps: [{name: xin-web, // 应用程序的名称script: npm, // 启动脚本args: run dev, // 启动脚本的参数cwd: /home/vue/xin_web, // Vite 项目的根目录interpreter: none,…...

前端教程-H5游戏开发

Egret EGRETIA RC 版本正式发布 从端到云一站式区块链游戏开发工作流 官网 Laya Air 在渲染模式上&#xff0c;LayaAir 支持 Canvas 和 WebGL 两种方式&#xff1b;在工具流的支持程度上&#xff0c;主要是提供了 LayaAir IDE。LayaAir IDE 包括代码模式与设计模式&#xff…...

Nginx 关闭/屏蔽 PUT、DELETE、OPTIONS 请求

1、修改 nginx 配置 在 nginx 配置文件中&#xff0c;增加如下配置内容&#xff1a; if ($request_method !~* GET|POST|HEAD) {return 403; }修改效果如下&#xff1a; 2、重启 nginx 服务 systemctl restart nginx或者 service nginx restart3、功能验证 使用如下方式…...

【React】React概念、特点和Jsx基础语法

React是什么&#xff1f; React 是一个用于构建用户界面的 JavaScript 库。 是一个将数据渲染为 HTML 视图的开源 JS 库它遵循基于组件的方法&#xff0c;有助于构建可重用的 UI 组件它用于开发复杂的交互式的 web 和移动 UI React有什么特点 使用虚拟 DOM 而不是真正的 DO…...

大数据的崭露头角:数据湖与数据仓库的融合之道

文章目录 数据湖与数据仓库的基本概念数据湖&#xff08;Data Lake&#xff09;数据仓库&#xff08;Data Warehouse&#xff09; 数据湖和数据仓库的优势和劣势数据湖的优势数据湖的劣势数据仓库的优势数据仓库的劣势 数据湖与数据仓库的融合之道1. 数据分类和标记2. 元数据管…...

用go实现cors中间件

目录 一、概述 二、简单请求和预检请求 简单请求 预检请求 三、使用go的gin框架实现cors配置 1、安装 2、函数 一、概述 CORS&#xff08;Cross-Origin Resource Sharing&#xff09;是一种浏览器安全机制&#xff0c;用于控制在Web应用程序中不同源&#xff08;Origin&a…...

Linux 链表示例 LIST_INIT LIST_INSERT_HEAD

list(3) — Linux manual page 用Visual Studio 2022创建CMake项目 * CmakeLists.txt # CMakeList.txt : Top-level CMake project file, do global configuration # and include sub-projects here. # cmake_minimum_required (VERSION 3.12)project ("llist")# I…...