Вопрос

I use the following code to get the cpu percetange (something like 62.5465%) but it seems to take a long time to refresh/update unless you manually navigate to another activity and then back. Is there any way to force the information to update every second for example? Any herlp would be appreciated.

private String ReadCPUinfo()
 {
  ProcessBuilder cmd;
  String result="";

  try{
   String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
   cmd = new ProcessBuilder(args);

   Process process = cmd.start();
   InputStream in = process.getInputStream();
   byte[] re = new byte[1024];
   while(in.read(re) != -1){
    System.out.println(new String(re));
    result = result + new String(re);
   }
   in.close();
  } catch(IOException ex){
   ex.printStackTrace();
  }
  return result;
 }

Used to display the text in a TextView.

device.setText(Html.fromHtml(  
"CPU Speed: "  + readUsage() * 100 
));
Это было полезно?

Решение

Timer and TimerTask can be used.

Timer timer = new Timer();
MyTimerTask myTimerTask = new MyTimerTask();

timer.schedule(myTimerTask, 0, 1000); // 0 Delay, Repeat after 1 second

Your MyTimerTask should look like this

class MyTimerTask extends TimerTask 
{
    public void run() 
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run() 
            {
                device.setText(Html.fromHtml("CPU Speed: " + readUsage() * 100));
            }
        }
    }
}

Edit

You can also use this method

device.postDelayed(new Runnable() 
{
    @Override
    public void run() 
    {
        device.setText(Html.fromHtml("CPU Speed: " + readUsage() * 100));
    }
}, 1000);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top