You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在自研APP中展示CPU、内存等性能数据?含Android Studio Profiler方案

在Android应用内展示CPU、内存及能耗数据的实现方案

CPU负载获取

通过读取系统/proc/stat文件计算CPU使用率,这是原生无依赖的实现方式:

public static float getCpuUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();
        String[] toks = load.split(" ");
        
        long idle1 = Long.parseLong(toks[5]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
        
        Thread.sleep(360);
        
        reader.seek(0);
        load = reader.readLine();
        reader.close();
        
        toks = load.split(" ");
        
        long idle2 = Long.parseLong(toks[5]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
        
        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}

注:需在子线程中执行,避免阻塞UI线程。

内存数据获取

利用系统ActivityManager和Debug类,可获取应用自身及系统内存状态:

// 获取应用已用内存(字节)
public static long getAppUsedMemory(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    Debug.MemoryInfo debugMemoryInfo = new Debug.MemoryInfo();
    Debug.getMemoryInfo(debugMemoryInfo);
    return debugMemoryInfo.getTotalPss() * 1024;
}

// 获取系统剩余内存(字节)
public static long getSystemFreeMemory(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
    am.getMemoryInfo(memoryInfo);
    return memoryInfo.availMem;
}

能耗数据获取

Android无直接返回能耗数值的API,可通过电池状态结合硬件使用情况估算:

// 获取电池剩余电量百分比
public static int getBatteryLevel(Context context) {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = context.registerReceiver(null, ifilter);
    
    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    
    return (int) ((level / (float) scale) * 100);
}

// 获取电池充放电状态
public static String getBatteryStatus(Context context) {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = context.registerReceiver(null, ifilter);
    
    int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
            status == BatteryManager.BATTERY_STATUS_FULL;
    
    int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    
    if (isCharging) {
        return usbCharge ? "USB充电中" : acCharge ? "AC充电中" : "充电中";
    } else {
        return "放电中";
    }
}

若需更精确能耗统计,可在API 26及以上使用UsageStatsManager结合硬件使用时长估算,需申请android.permission.PACKAGE_USAGE_STATS权限。

UI实时展示

通过LiveData或Handler将数据更新到UI组件,示例如下:

class SystemMetricsViewModel : ViewModel() {
    private val _cpuUsage = MutableLiveData<Float>()
    val cpuUsage: LiveData<Float> = _cpuUsage
    
    private val _appMemory = MutableLiveData<Long>()
    val appMemory: LiveData<Long> = _appMemory
    
    private val timer = Timer()
    
    init {
        timer.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                val cpu = getCpuUsage()
                _cpuUsage.postValue(cpu)
                
                val memory = getAppUsedMemory(ApplicationProvider.getApplicationContext())
                _appMemory.postValue(memory)
            }
        }, 0, 1000)
    }
    
    override fun onCleared() {
        super.onCleared()
        timer.cancel()
    }
}

内容的提问来源于stack exchange,提问作者Harmony Valley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:40:38