【工作笔记002】android 实现设备cpu与内存使用率监测

一、cpu使用率监测

1.首先需要给与app读取系统底层日志的权限

<uses-permission android:name="android.permission.READ_LOGS" />

2.通过读取系统日志计算出短时间内设备的cpu使用率(0~100):

/**
     * 读取当前cpu使用率
     */
    public  int readUsage()
    {
        try
        {
            BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream( "/proc/stat" ) ), 1000 );
            String load = reader.readLine();
            reader.close();

            String[] toks = load.split(" ");

            long currTotal = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]);
            long currIdle = Long.parseLong(toks[5]);
            long sum=(currTotal - total + currIdle - idle);
            if (sum>0){
                this.usage =(currTotal - total) * 100.0f /sum ;
            }
            this.total = currTotal;
            this.idle = currIdle;
        }
        catch( IOException ex )
        {
            ex.printStackTrace();
        }
        return (int) this.usage;
    }

二、内存使用监测—>当前app使用大小

public static int getMemPer(Context context){
        if (context==null){
            return 0;
        }
        ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        int[] pids=new int[1];
        pids[0]= Process.myPid();
        Debug.MemoryInfo[] processMemoryInfo = activityManager.getProcessMemoryInfo(pids);
        Debug.MemoryInfo memoryInfo = processMemoryInfo[0];
        Debug.getMemoryInfo(memoryInfo);
        int totalPss = memoryInfo.getTotalPss();
        return totalPss;//单位kb
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值