0

I found this code to get Cpu freq. in Android:

private String ReadCPUMhz()
        {
             ProcessBuilder cmd;
             String result="";
             int resultshow = 0;

             try{
              String[] args = {"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"};
              cmd = new ProcessBuilder(args);

              Process process = cmd.start();
              InputStream in = process.getInputStream();
              byte[] re = new byte[1024];
              while(in.read(re) != -1)
               {
                 result = result + new String(re);

               }

              in.close();
             } catch(IOException ex){
              ex.printStackTrace();
             }
             return result;
        }

The problem is that the result is in Khz and not Mhz so i get something like: 300000.. How can i convert in Mhz? A user wrote time ago that it found the solution using: result.trim() as you can see here Convert khz value from CPU into mhz or ghz but he doesn't explain how use it.. Anyone knows? Thanks

Community
  • 1
  • 1
David_D
  • 1,404
  • 4
  • 31
  • 65

2 Answers2

1

In the post you mentioned, the error

invalid int: "192000 "

is indeed avoided by using String.trim() before calling

Integer.parseInt(result);

Because in the String "192000 ", there is an extra space at the end that needs to be removed. The method trim() of class String removes leading and trailing whitespace:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim%28%29

So, based on your example code:

/* replace XXXX by the name of the
   class that holds method `ReadCPUMhz()`
*/
XXX instance = new XXX(); // supposing class XXX has such a constructor
String result = instance.ReadCPUMhz().trim(); // removes leading & trailing spaces
int kHzValue = Integer.parseInt(result); // result in kHz
int MHzResult = kHzValue / 1000; // result in MHz

should give the expected result in MHz.

Bludzee
  • 2,733
  • 5
  • 38
  • 46
0

Divide your result in Khz/1000 to get Mhz. Check this answer for the decimals thing: https://stackoverflow.com/a/10959430/2065418

tv.setText(new DecimalFormat("##.##").format(i2));
Community
  • 1
  • 1
Damien R.
  • 3,383
  • 1
  • 21
  • 32