由于是通过 cat /proc 的方式
所以
Process process = new ProcessBuilder()
.command("cat", "/proc/cpuinfo")
.redirectErrorStream(true)
.start();
和
String str1 = "/proc/meminfo";// 系统内存信息文件
String str2;
String[] arrayOfString;
long initial_memory = 0;
try {
FileReader localFileReader = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
两种方式是可以相互替换的。推荐使用 FileReader。
补充一个新的
// 返回 JVM 当前已分配的内存总量(包括已使用和未使用的部分)。
val total = Runtime.getRuntime().totalMemory()
// 返回当前未被使用的内存量。
val free = Runtime.getRuntime().freeMemory()
// 返回 JVM 能够使用的最大内存量(单位为字节)。
val max = Runtime.getRuntime().maxMemory()
// 获取 app 名称
private String app_name(Context context){
try {
// 获取app名称
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return context.getResources().getString(labelRes);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
// 获取屏幕分辨率
private String resolution(Context context){
try {
// 获取屏幕分辨率
//从系统服务中获取窗口管理器
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm=new DisplayMetrics();
//从默认显示器中获取显示参数保存到dm对象中
wm.getDefaultDisplay().getMetrics(dm);
return dm.widthPixels+"x"+dm.heightPixels;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
// 获取网络链接方式
private String access(Context context){
String access = "unknow";
try {
// 检查网络的链接方式
if (NetUtils.getInstance().isWifiConnected(context)){
access = "wifi";
}else if (NetUtils.getInstance().isEthernetConnected(context)){
access = "lan";
}
} catch (Exception e) {
e.printStackTrace();
}
return access;
}
/**
* 获取 CPU 核心数
*
* @return 可用的 CPU 核心数
*/
private int getCpuCoreCount() {
// 首先尝试使用 Runtime 方法
int coreCount = Runtime.getRuntime().availableProcessors();
// 如果核心数为 0,可以尝试从 /proc/cpuinfo 中获取
if (coreCount <= 0) {
coreCount = getCpuCoreCountFromProc();
}
return coreCount;
}
/**
* 从 /proc/cpuinfo 获取 CPU 核心数
*
* @return 核心数
*/
private int getCpuCoreCountFromProc() {
int coreCount = 0;
try {
Process process = new ProcessBuilder()
.command("cat", "/proc/cpuinfo")
.redirectErrorStream(true)
.start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
// 每当我们找到“processor”这一行时,就增加核心计数
if (line.startsWith("processor")) {
coreCount++;
}
}
bufferedReader.close();
process.waitFor(1, ); // 等待进程结束
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return coreCount;
}
// 获取可用空间
private String getInternalStorageAvailable() {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
return "";
}else {
try {
// 获取内部存储路径
StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
// 获取可用块数
long availableBlocks = 0;
availableBlocks = statFs.getAvailableBlocksLong();
// 获取每个块的大小
long blockSize = statFs.getBlockSizeLong();
// 计算可用的存储空间
long availableSpace = availableBlocks * blockSize;
return formatSize(availableSpace);
}catch (Exception e){
e.printStackTrace();
}
return "";
}
}
// 获取总空间
private String getInternalStorageTotal() {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
return "";
}else {
try {
// 获取内部存储路径
StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
// 获取总块数
long totalBlocks = statFs.getBlockCountLong();
// 获取每个块的大小
long blockSize = statFs.getBlockSizeLong();
// 计算总的存储空间
long totalSpace = totalBlocks * blockSize;
return formatSize(totalSpace);
}catch (Exception e){
e.printStackTrace();
}
return "";
}
}
/**
* 获取android总运行内存大小
* @return 单位 Byte
*/
private long getTotalMemory() {
String str1 = "/proc/meminfo";// 系统内存信息文件
String str2;
String[] arrayOfString;
long initial_memory = 0;
try {
FileReader localFileReader = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
str2 = localBufferedReader.readLine();// 读取meminfo第一行,系统总内存大小
arrayOfString = str2.split("\\s+");
for (String num : arrayOfString) {
Log.i(str2, num + "\t");
}
// 获得系统总内存,单位是KB
int i = Integer.valueOf(arrayOfString[1]).intValue();
//int值乘以1024转换为long类型
initial_memory = new Long((long) i * 1024);
localBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return initial_memory;// Byte转换为KB或者MB,内存大小规格化
}
/**
* 使用 ActivityManager 获取剩余可用内存的大小
* @param context 上下文
* */
public String getMemoryAvailable(Context context) {
try {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (activityManager != null) {
// 获取可用内存
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
// 可用内存
long availableMemory = memoryInfo.availMem;
// System.out.println("可用内存: " + formatSize(availableMemory));
return formatSize(availableMemory);
// 获取当前应用占用的内存信息
// Debug.MemoryInfo debugMemoryInfo = new Debug.MemoryInfo();
// Debug.getMemoryInfo(debugMemoryInfo);
// long pss = debugMemoryInfo.getTotalPss() * 1024; // 转换为字节
// System.out.println("当前应用占用的内存(PSS): " + formatSize(pss));
}
}catch (Exception e){
e.printStackTrace();
}
return "";
}
/**
* 使用 meminfo 获取可用内存大小
* */
public String getMemoryAvailable() {
String memInfoFilePath = "/proc/meminfo";
long availableMemory = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(memInfoFilePath))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("MemAvailable:")) { // 查找 MemAvailable 行
String[] parts = line.split("\\s+");
availableMemory = Long.parseLong(parts[1]) * 1024; // 转换为字节
break;
}
}
return formatSize(availableMemory);
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
// 格式化大小为可读字符串
private String formatSize(long size) {
String suffix = null;
float fSize = size;
if (size >= 1024) {
suffix = "KB";
fSize /= 1024;
}
if (fSize >= 1024) {
suffix = "MB";
fSize /= 1024;
}
if (fSize >= 1024) {
suffix = "GB";
fSize /= 1024;
}
return String.format("%.2f %s", fSize, suffix);
}
fun getMemoryFree(): Long {
val memInfoFilePath = "/proc/meminfo"
var availableMemory: Long = 0
try {
BufferedReader(FileReader(memInfoFilePath)).use { reader ->
var line: String
while (reader.readLine().also { line = it } != null) {
if (line.startsWith("MemFree:")) { // 查找 MemAvailable 行
val parts = line.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
availableMemory = parts[1].toLong() * 1024 // 转换为字节
break
}
}
return availableMemory
}
} catch (e: IOException) {
e.printStackTrace()
}
return 0
}