Android获取当前设备的内存和CPU使用情况

要获取当前设备的内存和CPU使用情况,你可以使用Android的系统API。下面是一种实现方式:

1 获取应用程序的内存使用情况:

ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);

long availableMemory = memoryInfo.availMem;
long totalMemory = memoryInfo.totalMem;

// 可用内存和总内存(以字节为单位)


2 获取应用程序的CPU使用情况:

Debug.MemoryInfo[] processMemoryInfo = Debug.getProcessMemoryInfo(new int[]{android.os.Process.myPid()});
int cpuUsage = processMemoryInfo[0].getTotalCpuTime();

// CPU使用时间(以毫秒为单位)



3 获取整个设备的内存使用情况:

ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);

long availableMemory = memoryInfo.availMem;
long totalMemory = memoryInfo.totalMem;

// 可用内存和总内存(以字节为单位)

4 获取整个设备的CPU使用情况:

RandomAccessFile reader = null;
try {
    reader = new RandomAccessFile("/proc/stat", "r");
    String load = reader.readLine();

    // 将读取到的数据进行解析,获取CPU使用时间
} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


以上代码片段可以帮助你获取设备和应用程序的内存和CPU使用情况。请注意,这些代码需要在合适的上下文中调用,例如在Activity或Service中。另外,还需根据你的需求对数据进行格式化和展示。