CPU使用率

package com.example.a82354.cpuuseage;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int REFRESH = 0x000001;
    public TextView tv = null;
    long total = 0;
    long idle = 0;
    double usage = 0;
    Button button;
   //private ProcessCpuTracker processCpuTracker=null;
    Handler handler = new Handler(){
       @Override
       public void handleMessage(Message msg) {
          // super.handleMessage(msg);
           Log.i("zhaoyi","handler");
           tv.setText(""+getUsage());
       }
   };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.activity_main);


        tv = (TextView) findViewById(R.id.system_memory);

        button= (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }
    //获得CPU使用率
    public double getUsage() {
        double usage = 0;
        long total_start, total_end;
        long idel_start, idel_end;

        try {
          Log.i("zhaoyi","jinrugetuseage");
            Map<String, Long> start_data = getCPUData();
            idel_start = start_data.get("idle");
            total_start = start_data.get("total_time");

            Thread.sleep(1000);

            Map<String, Long> end_data = getCPUData();
            idel_end = end_data.get("idle");
            total_end = end_data.get("total_time");

            double idel = idel_end - idel_start;
            double total = total_end - total_start;
            if (total == 0) {
                return 0;
            }
            usage = (total - idel) / total;
            usage = Math.abs(usage * 100);

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DecimalFormat df = new java.text.DecimalFormat("#.00");
        usage = Double.parseDouble(df.format(usage));
        handler.sendEmptyMessage(0x11);
        return usage;
    }
    public Map<String, Long> getCPUData() {
        Map<String, Long> data = new HashMap<String, Long>();
        ArrayList<Long> list = new ArrayList<Long>();
        ArrayList<Long> list_defalut = new ArrayList<Long>();
        for (int i = 0; i < 10; i++) {
            list_defalut.add(0L);
        }
//        String cpuCompare = "cpu" + CPU_index;
//        if (CPU_index == -1) {
//            cpuCompare = "cpu";
//        }
        String load = "";
        String[] temp = null;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream("/proc/stat")), 1000);
            load = reader.readLine();
//            while ((load = reader.readLine()) != null) {
//                if (load.contains(cpuCompare)) {
//                    break;
//                } else {
//                    load = "";
//                }
//            }
            reader.close();
            if (load == null || load.equals("")) {
                Log.i("zhaoyi","huodelekongzhi");
                data.put("total_time", 0L);
                data.put("idle", 0L);
                return data;
            }
            temp = load.split(" ");

            for (int i = 1; i < temp.length; i++) {
                Log.i("zhaoyi","youshuju");
                if (!temp[i].trim().equals("")) {
                    list.add(Long.parseLong(temp[i]));
                }
            }

        } catch (IOException ex) {
            Log.e("CPU", "IOException" + ex.toString());
            data.put("total_time", 0L);
            data.put("idle", 0L);
            return data;
        }
        long total_time = 0;
        for (int i = 0; i < list.size(); i++) {
            total_time += list.get(i);
        }
        data.put("total_time", total_time);
        data.put("idle", list.get(3));
        Log.i("zhaoyi","total_time="+total_time+"   idle   = "+list.get(3));
        return data;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button:
               // tv.setText(/*getProcessCpuRate()+""*/""+getUsage());
                Log.i("zhaoyi","dianjishijian");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("zhaoyi","jinruxiancheng");
                        getUsage();

                    }
                }).start();
                break;
        }
    }



















//
//    public double getUsage( )
//    {
//        readUsage( );
//        return usage;
//    }
//    public void 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]);
//
//            this.usage =(currTotal - total) * 100.0f / (currTotal - total + currIdle - idle);
//            this.total = currTotal;
//            this.idle = currIdle;
//        }
//        catch( IOException ex )
//        {
//            ex.printStackTrace();
//        }
//
//    }
//
//    public static float getProcessCpuRate()
//    {
//
//        float totalCpuTime1 = getTotalCpuTime();
//        float processCpuTime1 = getAppCpuTime();
//        try
//        {
//            Thread.sleep(360);
//
//        }
//        catch (Exception e)
//        {
//        }
//
//        float totalCpuTime2 = getTotalCpuTime();
//        float processCpuTime2 = getAppCpuTime();
//
//        float cpuRate = 100 * (processCpuTime2 - processCpuTime1)
//                / (totalCpuTime2 - totalCpuTime1);
//
//        return cpuRate;
//    }
//    public static long getTotalCpuTime()
//    { // 获取系统总CPU使用时间
//        String[] cpuInfos = null;
//        try
//        {
//            BufferedReader reader = new BufferedReader(new InputStreamReader(
//                    new FileInputStream("/proc/stat")), 1000);
//            String load = reader.readLine();
//            reader.close();
//            cpuInfos = load.split(" ");
//        }
//        catch (IOException ex)
//        {
//            ex.printStackTrace();
//        }
//        long totalCpu = Long.parseLong(cpuInfos[2])
//                + Long.parseLong(cpuInfos[3]) + Long.parseLong(cpuInfos[4])
//                + Long.parseLong(cpuInfos[6]) + Long.parseLong(cpuInfos[5])
//                + Long.parseLong(cpuInfos[7]) + Long.parseLong(cpuInfos[8]);
//        return totalCpu;
//    }
//
//    public static long getAppCpuTime()
//    { // 获取应用占用的CPU时间
//        String[] cpuInfos = null;
//        try
//        {
//            int pid = android.os.Process.myPid();
//            BufferedReader reader = new BufferedReader(new InputStreamReader(
//                    new FileInputStream("/proc/" + pid + "/stat")), 1000);
//            String load = reader.readLine();
//            reader.close();
//            cpuInfos = load.split(" ");
//        }
//        catch (IOException ex)
//        {
//            ex.printStackTrace();
//        }
//        long appCpuTime = Long.parseLong(cpuInfos[13])
//                + Long.parseLong(cpuInfos[14]) + Long.parseLong(cpuInfos[15])
//                + Long.parseLong(cpuInfos[16]);
//        return appCpuTime;
//    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值