• 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;
    
    // 可用内存和总内存(以字节为单位)
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

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

    Debug.MemoryInfo[] processMemoryInfo = Debug.getProcessMemoryInfo(new int[]{android.os.Process.myPid()});
    int cpuUsage = processMemoryInfo[0].getTotalCpuTime();
    
    // CPU使用时间(以毫秒为单位)
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    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;
    
    // 可用内存和总内存(以字节为单位)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    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();
            }
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

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

  • 相关阅读:
    【AI视野·今日NLP 自然语言处理论文速览 第五十二期】Wed, 11 Oct 2023
    【C++笔记 】第一篇 注释和打印
    es查询限制10000,使用scroll
    HTML这一篇就够啦~
    Python学习十:网络编程
    Redis足足十二题,应该没有人能全对
    Go中原生http服务的实现方式
    SpringCloud 三种服务调用方式,你学会了吗?
    高精度算法【加减乘除】
    http库requests
  • 原文地址:https://blog.csdn.net/oHeHui1/article/details/133922639