获取 apk内存占用率和cpu占用率

1.内存占用率

return String.format(Locale.ENGLISH, "%.2f", Double.parseDouble(getUsage("dumpsys meminfo -s "+t.getPackageName(),t.getPackageName()))/Double.parseDouble(Total())*100);
    public String Total() {
        String result = "";
        try {
            ActivityManager am = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
            ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
            am.getMemoryInfo(mi);
            result = String.valueOf(mi.totalMem/1024);
        } catch (Exception e) {
            LogUtils.e(TAG+" Total memory :" + e.toString());
        }

        LogUtils.d(TAG + " result = " + result);
        return  (result != null) ? result:"";
    }

 串口命令

dumpsys meminfo 包名 |grep RSS  

2.cpu占用率

getUsage("dumpsys cpuinfo",t.getPackageName());

 串口命令 

dumpsys cpuinfo |grep 包名

3.代码实现

    public String getUsage(String command,String packageName) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            InputStream inputStream = process.getInputStream();
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(inputStream));
            String line = null;
           
                while ((line = lnr.readLine()) != null ) {
                    if (command.contains("cpuinfo")){
                        if (line.contains(packageName)){
                            return line.split("%",2)[0];
                        }
                    }else if (command.contains("meminfo")){
                        if (line.contains("TOTAL RSS")){
                            return line.split("TOTAL RSS:",2)[1].split("T",2)[0];
                        }
                    }
        
                }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaowang_lj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值