1、CPU频率,CPU信息:/proc/cpuinfo和/proc/stat
通过读取文件/proc/cpuinfo系统CPU的类型等多种信息。
读取/proc/stat 所有CPU活动的信息来计算CPU使用率
下面我们就来讲讲如何通过代码来获取CPU频率:
复制代码 代码如下:
package com.orange.cpu
import java.io.BufferedReader
import java.io.FileNotFoundException
import java.io.FileReader
import java.io.IOException
import java.io.InputStream
public class CpuManager {
// 获取CPU最大频率(单位KHZ)
// "/system/bin/cat" 命令行
// "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" 存储最大频率的文件的.路径
public static String getMaxCpuFreq() {
String result = ""
ProcessBuilder cmd
try {
String[] args = { "/system/bin/cat",
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" }
cmd = new ProcessBuilder(args)
Process process = cmd.start()
InputStream in = process.getInputStream()
byte[] re = new byte[24]
while (in.read(re) != -1) {
result = result + new String(re)
}
in.close()
} catch (IOException ex) {
ex.printStackTrace()
result = "N/A"
}
return result.trim()
}
// 获取CPU最小频率(单位KHZ)
public static String getMinCpuFreq() {
String result = ""
ProcessBuilder cmd
try {
String[] args = { "/system/bin/cat",
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" }
cmd = new ProcessBuilder(args)
Process process = cmd.start()
InputStream in = process.getInputStream()
byte[] re = new byte[24]
while (in.read(re) != -1) {
result = result + new String(re)
}
in.close()
} catch (IOException ex) {
ex.printStackTrace()
result = "N/A"
}
return result.trim()
}
// 实时获取CPU当前频率(单位KHZ)
public static String getCurCpuFreq() {
String result = "N/A"
try {
FileReader fr = new FileReader(
"/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq")
BufferedReader br = new BufferedReader(fr)
String text = br.readLine()
result = text.trim()
} catch (FileNotFoundException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
}
return result
}
// 获取CPU名字
public static String getCpuName() {
try {
FileReader fr = new FileReader("/proc/cpuinfo")
BufferedReader br = new BufferedReader(fr)
String text = br.readLine()
String[] array = text.split(":s+", 2)
for (int i = 0i <array.lengthi++) {
}
return array[1]
} catch (FileNotFoundException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
}
return null
}
}
2、内存:/proc/meminfo
复制代码 代码如下:
public void getTotalMemory() {
String str1 = "/proc/meminfo"
String str2=""
try {
FileReader fr = new FileReader(str1)
BufferedReader localBufferedReader = new BufferedReader(fr, 8192)
while ((str2 = localBufferedReader.readLine()) != null) {
Log.i(TAG, "---" + str2)
}
} catch (IOException e) {
}
}
3、Rom大小
复制代码 代码如下:
public long[] getRomMemroy() {
long[] romInfo = new long[2]
//Total rom memory
romInfo[0] = getTotalInternalMemorySize()
//Available rom memory
File path = Environment.getDataDirectory()
StatFs stat = new StatFs(path.getPath())
long blockSize = stat.getBlockSize()
long availableBlocks = stat.getAvailableBlocks()
romInfo[1] = blockSize * availableBlocks
getVersion()
return romInfo
}
public long getTotalInternalMemorySize() {
File path = Environment.getDataDirectory()
StatFs stat = new StatFs(path.getPath())
long blockSize = stat.getBlockSize()
long totalBlocks = stat.getBlockCount()
return totalBlocks * blockSize
}
4、sdCard大小
复制代码 代码如下:
public long[] getSDCardMemory() {
long[] sdCardInfo=new long[2]
String state = Environment.getExternalStorageState()
if (Environment.MEDIA_MOUNTED.equals(state)) {
File sdcardDir = Environment.getExternalStorageDirectory()
StatFs sf = new StatFs(sdcardDir.getPath())
long bSize = sf.getBlockSize()
long bCount = sf.getBlockCount()
long availBlocks = sf.getAvailableBlocks()
sdCardInfo[0] = bSize * bCount//总大小
sdCardInfo[1] = bSize * availBlocks//可用大小
}
return sdCardInfo
}
5、电池电量
复制代码 代码如下:
private BroadcastReceiver batteryReceiver=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra("level", 0)
// level加%就是当前电量了
}
}
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED))
6、系统的版本信息
复制代码 代码如下:
public String[] getVersion(){
String[] version={"null","null","null","null"}
String str1 = "/proc/version"
String str2
String[] arrayOfString
try {
FileReader localFileReader = new FileReader(str1)
BufferedReader localBufferedReader = new BufferedReader(
localFileReader, 8192)
str2 = localBufferedReader.readLine()
arrayOfString = str2.split("s+")
version[0]=arrayOfString[2]//KernelVersion
localBufferedReader.close()
} catch (IOException e) {
}
version[1] = Build.VERSION.RELEASE// firmware version
version[2]=Build.MODEL//model
version[3]=Build.DISPLAY//system version
return version
}
7、mac地址和开机时间
复制代码 代码如下:
public String[] getOtherInfo(){
String[] other={"null","null"}
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE)
WifiInfo wifiInfo = wifiManager.getConnectionInfo()
if(wifiInfo.getMacAddress()!=null){
other[0]=wifiInfo.getMacAddress()
} else {
other[0] = "Fail"
}
other[1] = getTimes()
return other
}
private String getTimes() {
long ut = SystemClock.elapsedRealtime() / 1000
if (ut == 0) {
ut = 1
}
int m = (int) ((ut / 60) % 60)
int h = (int) ((ut / 3600))
return h + " " + mContext.getString(R.string.info_times_hour) + m + " "
+ mContext.getString(R.string.info_times_minute)
}
因为Android本质上是linux系统,所以关系硬件相关的信息实际上是用文件表示的
CPU相关信息放在 /sys/devices/system/cpu/ 这个路径下,
要知道cpu的核数只需要查看这个路径中的文件即可
如果CPU是双核的,则 /sys/devices/system/cpu/ 路径下有两个子文件夹 cpu0 和 cpu1
如果CPU是四核的,则 /sys/devices/system/cpu/ 路径下有四个子文件夹 cpu0 和 cpu1 和 cpu2 和 cpu3
以此类推
这个是抄来的
获取 CPU 核数Linux 中的设备都是以文件的形式存在,CPU 也不例外,因此 CPU 的文件个数就等价与核数。Android 的 CPU 设备文件位于/sys/devices/system/cpu/目录,文件名的的格式为cpu\d+。root@generic_x86_64:/sys/devices/system/cpu # ls cpu0 cpufreqcpuidlekernel_maxmodaliasofflineonlinepossiblepowerpresentuevent统计一下文件个数便可以获得 CPU 核数。public static int getNumberOfCPUCores() { 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 Gingerbreadthat can let an app in the background run without impacting// the foreground application. But for our purposes, it makes them single core.return 1 } int cores try {cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length } catch (SecurityException e) {cores = DEVICEINFO_UNKNOWN } catch (NullPointerException e) {cores = DEVICEINFO_UNKNOWN } return cores}private static final FileFilter CPU_FILTER = new FileFilter() { @Override public boolean accept(File pathname) {String path = pathname.getName()//regex is slow, so checking char by char.if (path.startsWith("cpu")) { for (int i = 3i <path.length()i++) {if (path.charAt(i) <'0' path.charAt(i) >'9') { return false} } return true}return false }}获取时钟频率获取时钟频率需要读取系统文件 -/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq或者/proc/cpuinfo。 Android 模拟器中并没有cpuinfo_max_freq文件,因此只能读取/proc/cpuinfo。/proc/cpuinfo包含了很多 cpu 数据。processor: 0vendor_id: GenuineIntelcpu family: 6model: 70model name: Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHzstepping: 1cpu MHz: 0.000cache size: 1024 KBfdiv_bug: nohlt_bug: nof00f_bug: nocoma_bug: nofpu: yesfpu_exception: yescpuid level: 4wp: yes代码如下:public static int getCPUMaxFreqKHz() { int maxFreq = DEVICEINFO_UNKNOWN try {for (int i = 0i <getNumberOfCPUCores()i++) { String filename = "/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq" File cpuInfoMaxFreqFile = new File(filename) if (cpuInfoMaxFreqFile.exists()) {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 (buffer[endIndex] >= '0' &&buffer[endIndex] <= '9' &&endIndex <buffer.length) endIndex++ String str = new String(buffer, 0, endIndex) Integer freqBound = Integer.parseInt(str) if (freqBound >maxFreq) maxFreq = freqBound} catch (NumberFormatException e) { //Fall through and use /proc/cpuinfo.} finally { stream.close()} }}if (maxFreq == DEVICEINFO_UNKNOWN) { FileInputStream stream = new FileInputStream("/proc/cpuinfo") try {int freqBound = parseFileForValue("cpu MHz", stream)freqBound *= 1000//MHz ->kHzif (freqBound >maxFreq) maxFreq = freqBound } finally {stream.close() }} } catch (IOException e) {maxFreq = DEVICEINFO_UNKNOWN//Fall through and return unknown. } return maxFreq}获取内存大小如果 SDK 版本大于等于JELLY_BEAN,可以通过ActivityManager来获取内从大小。ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo()ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE)am.getMemoryInfo(memInfo)如果版本低于JELLY_BEAN,则只能读取系统文件了。FileInputStream stream = new FileInputStream("/proc/meminfo")totalMem = parseFileForValue("MemTotal", stream)完整代码如下:@TargetApi(Build.VERSION_CODES.JELLY_BEAN)public static long getTotalMemory(Context c) { // 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} else { return DEVICEINFO_UNKNOWN} } else {long totalMem = DEVICEINFO_UNKNOWNtry { FileInputStream stream = new FileInputStream("/proc/meminfo") try {totalMem = parseFileForValue("MemTotal", stream)totalMem *= 1024 } finally {stream.close() }} catch (IOException e) {}return totalMem }}欢迎分享,转载请注明来源:内存溢出
评论列表(0条)