首页 > 其他分享 >获得android手机的CPU核心数

获得android手机的CPU核心数

时间:2023-04-30 11:06:27浏览次数:46  
标签:10 return String system long new 手机 android CPU




//CPU个数
private int getNumCores() {
    //Private Class to display only CPU devices in the directory listing
    class CpuFilter implements FileFilter {
        @Override
        public boolean accept(File pathname) {
            //Check if filename is "cpu", followed by a single digit number
            if(Pattern.matches("cpu[0-9]", pathname.getName())) {
                return true;
            }
            return false;
        }      
    }

    try {
        //Get directory containing CPU info
        File dir = new File("/sys/devices/system/cpu/");
        //Filter to only list the devices we care about
        File[] files = dir.listFiles(new CpuFilter());
        Log.d(TAG, "CPU Count: "+files.length);
        //Return the number of cores (virtual CPU devices)
        return files.length;
    } catch(Exception e) {
        //Print exception
        Log.d(TAG, "CPU Count: Failed.");
        e.printStackTrace();
        //Default to return 1 core
        return 1;
    }
}


不需要root权限。

/sys/devices/system/cpu/cpu0 ----------Cpu1

/sys/devices/system/cpu/cpu1 ----------Cpu2

获取CPU最大频率:

   // "/system/bin/cat" 命令行
   




1. public static long getCpuFrequence() {  
2.        ProcessBuilder cmd;  
3.        try {  
4.            String[] args = { "/system/bin/cat",  
5.                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };  
6.            cmd = new ProcessBuilder(args);  
7.  
8.            Process process = cmd.start();  
9.            BufferedReader reader = new BufferedReader(new InputStreamReader(  
10.                    process.getInputStream()));  
11.            String line = reader.readLine();  
12.            return StringUtils.parseLongSafe(line, 10, 0);  
13.        } catch (IOException ex) {  
14.            ex.printStackTrace();  
15.        }  
16.        return 0;  
17.    }



// 获取CPU最小频率(单位KHZ):




    1. public static String getMinCpuFreq() {  
    2.            String result = "";  
    3.            ProcessBuilder cmd;  
    4.            try {  
    5.                    String[] args = { "/system/bin/cat",  
    6.                                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" };  
    7.                    cmd = new ProcessBuilder(args);  
    8.                    Process process = cmd.start();  
    9.                    InputStream in = process.getInputStream();  
    10.                    byte[] re = new byte[24];  
    11.                    while (in.read(re) != -1) {  
    12.                            result = result + new String(re);  
    13.                    }  
    14.                    in.close();  
    15.            } catch (IOException ex) {  
    16.                    ex.printStackTrace();  
    17.                    result = "N/A";  
    18.            }  
    19.            return result.trim();  
    20.    }





    // 实时获取CPU当前频率(单位KHZ):



    1. public static String getCurCpuFreq() {  
    2.              String result = "N/A";  
    3.              try {  
    4.                      FileReader fr = new FileReader(  
    5.                                      "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");  
    6.                      BufferedReader br = new BufferedReader(fr);  
    7.                      String text = br.readLine();  
    8.                      result = text.trim();  
    9.              } catch (FileNotFoundException e) {  
    10.                      e.printStackTrace();  
    11.              } catch (IOException e) {  
    12.                      e.printStackTrace();  
    13.              }  
    14.              return result;  
    15.      }


    / 获取CPU名字:



    1. public static String getCpuName() {  
    2.             try {  
    3.                     FileReader fr = new FileReader("/proc/cpuinfo");  
    4.                     BufferedReader br = new BufferedReader(fr);  
    5.                     String text = br.readLine();  
    6.                     String[] array = text.split(":\\s+", 2);  
    7.                     for (int i = 0; i < array.length; i++) {  
    8.                     }  
    9.                     return array[1];  
    10.             } catch (FileNotFoundException e) {  
    11.                     e.printStackTrace();  
    12.             } catch (IOException e) {  
    13.                     e.printStackTrace();  
    14.             }  
    15.             return null;  
    16.     }


    内存:/proc/meminfo:


    1. public void getTotalMemory() {    
    2.        String str1 = "/proc/meminfo";    
    3.        String str2="";    
    4.        try {    
    5.            FileReader fr = new FileReader(str1);    
    6.            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);    
    7.            while ((str2 = localBufferedReader.readLine()) != null) {    
    8.                Log.i(TAG, "---" + str2);    
    9.            }    
    10.        } catch (IOException e) {    
    11.        }    
    12.    }




    www.2cto.com



      1. public long[] getRomMemroy() {    
      2.        long[] romInfo = new long[2];    
      3.        //Total rom memory     
      4.        romInfo[0] = getTotalInternalMemorySize();    
      5.     
      6.        //Available rom memory     
      7.        File path = Environment.getDataDirectory();    
      8.        StatFs stat = new StatFs(path.getPath());    
      9.        long blockSize = stat.getBlockSize();    
      10.        long availableBlocks = stat.getAvailableBlocks();    
      11.        romInfo[1] = blockSize * availableBlocks;    
      12.        getVersion();    
      13.        return romInfo;    
      14.    }    
      15.     
      16.    public long getTotalInternalMemorySize() {    
      17.        File path = Environment.getDataDirectory();    
      18.        StatFs stat = new StatFs(path.getPath());    
      19.        long blockSize = stat.getBlockSize();    
      20.        long totalBlocks = stat.getBlockCount();    
      21.        return totalBlocks * blockSize;    
      22.    }



      sdCard大小:



      1. public long[] getSDCardMemory() {    
      2.        long[] sdCardInfo=new long[2];    
      3.        String state = Environment.getExternalStorageState();    
      4.        if (Environment.MEDIA_MOUNTED.equals(state)) {    
      5.            File sdcardDir = Environment.getExternalStorageDirectory();    
      6.            StatFs sf = new StatFs(sdcardDir.getPath());    
      7.            long bSize = sf.getBlockSize();    
      8.            long bCount = sf.getBlockCount();    
      9.            long availBlocks = sf.getAvailableBlocks();    
      10.     
      11.            sdCardInfo[0] = bSize * bCount;//总大小     
      12.            sdCardInfo[1] = bSize * availBlocks;//可用大小     
      13.        }    
      14.        return sdCardInfo;    
      15.    }



      系统的版本信息:



      1. public String[] getVersion(){    
      2.    String[] version={"null","null","null","null"};    
      3.    String str1 = "/proc/version";    
      4.    String str2;    
      5.    String[] arrayOfString;    
      6.    try {    
      7.        FileReader localFileReader = new FileReader(str1);    
      8.        BufferedReader localBufferedReader = new BufferedReader(    
      9.                localFileReader, 8192);    
      10.        str2 = localBufferedReader.readLine();    
      11.        arrayOfString = str2.split("\\s+");    
      12.        version[0]=arrayOfString[2];//KernelVersion     
      13.        localBufferedReader.close();    
      14.    } catch (IOException e) {    
      15.    }    
      16.    version[1] = Build.VERSION.RELEASE;// firmware version     
      17.    version[2]=Build.MODEL;//model     
      18.    version[3]=Build.DISPLAY;//system version     
      19.    return version;    
      20. }




      mac地址和开机时间



      1. public String[] getOtherInfo(){    
      2.    String[] other={"null","null"};    
      3.       WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);    
      4.       WifiInfo wifiInfo = wifiManager.getConnectionInfo();    
      5.       if(wifiInfo.getMacAddress()!=null){    
      6.        other[0]=wifiInfo.getMacAddress();    
      7.    } else {    
      8.        other[0] = "Fail";    
      9.    }    
      10.    other[1] = getTimes();    
      11.       return other;    
      12.    
      13. private String getTimes() {    
      14.    long ut = SystemClock.elapsedRealtime() / 1000;    
      15.    if (ut == 0) {    
      16.        ut = 1;    
      17.    }    
      18.    int m = (int) ((ut / 60) % 60);    
      19.    int h = (int) ((ut / 3600));    
      20.    return h + " " + mContext.getString(R.string.info_times_hour) + m + " "   
      21.            + mContext.getString(R.string.info_times_minute);    
      22. }


      ---------------------------------------------------

      1. private static void updateCpuStat() {  
      2.    ProcessBuilder cmd;  
      3.    long oldMypidStat = first ? 0 : mypidStat;  
      4.    long oldTotal = first ? 0 : total;  
      5.  
      6.    try {  
      7.        StringBuilder builder = new StringBuilder();  
      8.        int pid = android.os.Process.myPid();  
      9.        String[] args = { "/system/bin/cat", "/proc/" + pid + "/stat" };  
      10.        cmd = new ProcessBuilder(args);  
      11.  
      12.        Process process = cmd.start();  
      13.        InputStream in = process.getInputStream();  
      14.        byte[] re = new byte[1024];  
      15.        int len;  
      16.        while ((len = in.read(re)) != -1) {  
      17.            builder.append(new String(re, 0, len));  
      18.        }  
      19.        // Log.i(TAG, builder.toString());   
      20.        in.close();  
      21.  
      22.        String[] stats = builder.toString().split(" +", -1);  
      23.        if (stats.length >= 17) {  
      24.            long utime = StringUtils.parseLongSafe(stats[13], 10);  
      25.            long stime = StringUtils.parseLongSafe(stats[14], 10);  
      26.            long cutime = StringUtils.parseLongSafe(stats[15], 10);  
      27.            long cstime = StringUtils.parseLongSafe(stats[16], 10);  
      28.            // Log.i(TAG, String.format(   
      29.            // "utime:%d, stime:%d, cutime:%d, cstime:%d", utime,   
      30.            // stime, cutime, cstime));   
      31.            mypidStat = utime + stime + cutime + cstime;  
      32.        }  
      33.    } catch (IOException ex) {  
      34.        ex.printStackTrace();  
      35.    }  
      36.  
      37.    try {  
      38.        String[] args = { "/system/bin/cat", "/proc/stat" };  
      39.        cmd = new ProcessBuilder(args);  
      40.  
      41.        Process process = cmd.start();  
      42.        BufferedReader reader = new BufferedReader(new InputStreamReader(  
      43.                process.getInputStream()));  
      44.        String line = null;  
      45.        while ((line = reader.readLine()) != null) {  
      46.            Matcher matcher = pattern.matcher(line);  
      47.            if (matcher.matches()) {  
      48.                String[] stats = line.split(" +", -1);  
      49.                long tmpTotal = 0;  
      50.                for (int i = 1; i < stats.length; i++) {  
      51.                    tmpTotal += StringUtils.parseLongSafe(stats[i], 10);  
      52.                }  
      53.                total = tmpTotal;  
      54.            }  
      55.            break;  
      56.        }  
      57.        if (first) {  
      58.            first = false;  
      59.        } else {  
      60.            Log.i(TAG, String.format("vsir cpu usage: %2.1f%%",  
      61.                    (double) (mypidStat - oldMypidStat)  
      62.                            / (total - oldTotal) * 100));  
      63.        }  
      64.        reader.close();  
      65.    } catch (IOException ex) {  
      66.        ex.printStackTrace();  
      67.    }  
      68. }

      标签:10,return,String,system,long,new,手机,android,CPU
      From: https://blog.51cto.com/u_548275/6237782

      相关文章

      • Android中使用log4j
        如果要直接在android工程中使用log4j,是有点问题的,会报如下的错: 11-2309:44:56.947:D/dalvikvm(1585):GC_FOR_MALLOCfreed3278objects/311568bytesin31ms rejectingopcode0x21at0x000a rejectedLorg/apache/log4j/config/PropertySetter;.getPropertyDescript......
      • java-正则表达式判断手机号
        要更加准确的匹配手机号码只匹配11位数字是不够的,比如说就没有以144开始的号码段,故先要整清楚现在已经开放了多少个号码段,国家号码段分配如下:移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188联通:130、131、132、152、155、156、185、186......
      • Android ListView 去除…
        去除ListView滑到顶部和底部时边缘的黑色阴影:android:fadingEdge="none"----------------------------------------------------去除拖动时默认的黑色背景:android:cacheColorHint="#00000000" 或listView.setCacheColorHint(Color.TRANSPARENT);---------------------......
      • android上传图片至服务器
        本实例实现了android上传手机图片至服务器,服务器进行保存服务器servlet代码publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Stringtemp=request.getSession().getServle......
      • Android 开发 UI 规则
        Android的官方开发者博客发了一份幻灯片,介绍了一些AndroidUI设计的小贴士,在这里以看图说话的形式发出来。Don’t: 1、不要照搬你在其它平台的UI设计,应该让用户感觉是在真正使用一个Android软件,在你的商标显示和平台整体观感之间做好平衡2、不要过度使用模态对话框3、......
      • Android应用程序的国际化与本地化
        internationalization(国际化)简称i18n,因为在i和n之间还有18个字符,localization(本地化),简称L10n。 zh_CN,zh_TW. http://www.loc.gov/standards/iso639-2/php/code_list.phphttp://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html在Andro......
      • android中的像素单位dp、px、pt、s…
        pixels(设备独立像素).不同设备有不同的显示效果,这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA推荐使用这个,不依赖像素。px:pixels(像素).不同设备显示效果相同,一般我们HVGA代表320x480像素,这个用的比较多。pt:point,是一个标准的长度单位,1pt=1/72英寸,用于......
      • android中退出当前应用程序的四种…
        Android程序有很多Activity,比如说主窗口A,调用了子窗口B,如果在B中直接finish(),接下里显示的是A。在B中如何关闭整个Android应用程序呢?本人总结了几种比较简单的实现方法。1.DalvikVM的本地方法android.os.Process.killProcess(android.os.Process.myPid())//获取PID......
      • android TextView属性大全
        android:autoLink设置是否当文本为URL链接/email/电话号码/map时,文本显示为可点击的链接。可选值(none/web/email/phone/map/all)android:autoText如果设置,将自动执行输入值的拼写纠正。此处无效果,在显示输入法并输入的时候起作用。android:bufferType指定get......
      • Android Bitmap内存溢出问题解释
        Android平台在图片处理方面经常会出现OOM的问题,在去年开发的一个项目中,我也一直被这个问题所困扰,在这方面也搜集了许多的资料,今天仅仅针对Android平台的Bitmap说事儿,今后再对内存的问题做详细的探讨,android平台对图片解码这块确实设置的有内存上限,在解码Bitmap的时候android平台会......