当前位置:   article > 正文

Android,获取手机硬件信息(CPU、内存)工具类_android 获取内存、cpu和磁盘

android 获取内存、cpu和磁盘

kotlin版

import android.app.ActivityManager
import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.*

/**
 * 获取硬件信息工具类,如:CPU参数、内存参数等
 */
class HardwareInfoUtils {

    //获取CPU整体温度,单位:°C
    suspend fun getCPUTemperature() : Float{
        var temperature : String
        withContext(Dispatchers.IO){
            val temperatureOfCPUFileName = "/sys/class/thermal/thermal_zone0/temp"
            temperature = readCpuInfo(temperatureOfCPUFileName)
        }
        return temperature.toFloat()/1000.0F ?: 0.00F
    }

    /**
     * 获取CPU整体使用率,返回是"百分比"
     * 如返回:22.0,表示CPU占用率是22.0%
     */
    suspend fun getCPUUsage() : Float{
        var rate : Float = 0.00f
        withContext(Dispatchers.IO){
            var process : Process? = null
            try{
                process = Runtime.getRuntime().exec("top -n 1")
                val reader : BufferedReader = BufferedReader( InputStreamReader(process.inputStream))
                var line : String ?= null
                var cpuIndex = -1
                while((reader.readLine().also { line = it }) != null){
                    line = line!!.trim()
                    if(line == null){
                        continue
                    }
                    val tempIndex = getCPUIndex(line!!)
                    if(tempIndex != -1){
                        cpuIndex = tempIndex
                        continue
                    }
                    if(line!!.startsWith(android.os.Process.myPid().toString())){
                        if(cpuIndex == -1){
                            continue
                        }
                        val param = line!!.split("\\s+".toRegex())
                        if(param.size <= cpuIndex){
                            continue
                        }
                        var cpu = param[cpuIndex]
                        if(cpu.endsWith("%")){
                            cpu = cpu.substring(0,cpu.lastIndexOf("%"))
                        }
                        rate =  cpu.toFloat()/ Runtime.getRuntime().availableProcessors()
                        break
                    }
                }
            }catch (e : IOException){
                e.printStackTrace()
            }finally {
                if(process != null){
                    process.destroy()
                }
            }
        }
        return ((Math.round(rate*100))/100).toFloat()
    }

    //获取BaseFrequency
    suspend fun getBaseFrequency() : List<String>? {
        var cpuFreqs: List<String>? = null
        withContext(Dispatchers.IO) {
            val cpufreq0 =
                readCpuInfo("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq")
            val cpufreq1 =
                readCpuInfo("/sys/devices/system/cpu/cpu1/cpufreq/scaling_cur_freq")
            val cpufreq2 =
                readCpuInfo("/sys/devices/system/cpu/cpu2/cpufreq/scaling_cur_freq")
            val cpufreq3 =
                readCpuInfo("/sys/devices/system/cpu/cpu3/cpufreq/scaling_cur_freq")
            val cpufreq4 =
                readCpuInfo("/sys/devices/system/cpu/cpu4/cpufreq/scaling_cur_freq")
            val cpufreq5 =
                readCpuInfo("/sys/devices/system/cpu/cpu5/cpufreq/scaling_cur_freq")
            cpuFreqs = listOf(cpufreq0, cpufreq1, cpufreq2, cpufreq3, cpufreq4, cpufreq5)
        }
        return cpuFreqs
    }

    //获取系统总内存大小,单位:MB
    suspend fun getTotalMemory() : Int{
        val fileNameMemInfo = "/proc/meminfo"      //系统内存信息
        val str2 : String
        var total = 0
        withContext(Dispatchers.IO){
            try {
                val localFileReader : FileReader = FileReader(fileNameMemInfo)
                val localBufferedReader : BufferedReader = BufferedReader(localFileReader,8192);
                str2 = localBufferedReader.readLine();          //读取meminfo第一行:系统总内存大小
                val arrayOfString = str2.split(" ")
                localBufferedReader.close()
                total = arrayOfString[8].toInt()/1024
            }catch (e : IOException){
                e.printStackTrace()
            }
        }
        return total
    }

    //获取当前可用(剩余)运行内存大小,单位:MB
    suspend fun getAvailMemory(context: Context) : Int{
        var availMem : Int = 0
        withContext(Dispatchers.IO){
            val am : ActivityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val mi : ActivityManager.MemoryInfo = ActivityManager.MemoryInfo()
            try {
                am.getMemoryInfo(mi)
                availMem = (mi.availMem/1048576).toInt()         //转换成MB 1048576=1024*1024
            }catch (e : IOException){
                e.printStackTrace()
            }
        }
        return availMem
    }

    //获取当前应用内存占用,单位:MB
    suspend fun getAppOccupyMemory(context: Context) : Int {
        var memSize : Long = 0
        withContext(Dispatchers.IO){
            val am : ActivityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val pid = android.os.Process.myPid()
            val pids = intArrayOf(pid)
            try {
                val memInfo = am.getProcessMemoryInfo(pids)
                memSize = memInfo[0].totalPss.toLong()
            }catch (e: IOException){
                e.printStackTrace()
            }
        }
        return (memSize/1024).toInt()
    }

    //获取内存当前频率,单位:Mhz
    suspend fun getMemBaseFrequency() : Float{
        var fre = 0
        withContext(Dispatchers.IO){
            val memFreFileName = "/sys/devices/platform/dmc/devfreq/dmc/cur_freq"
            val dmcFreq = readCpuInfo(memFreFileName)
            val memFre = dmcFreq.split("\\s+".toRegex())
            fre = memFre[0].toLong().toInt()
        }
        return (fre/1000000.0).toFloat()                            //转换为Mhz
    }

    //根据文件路径读取CPU信息
    private fun readCpuInfo(path: String): String {
        val tempFile = File(path)
        if (!tempFile.exists()) return ""
        var input : FileInputStream ?= null
        try {
            input = FileInputStream(tempFile)
            val bytes = ByteArray(64)
            val leng = input.read(bytes)
            val temp = String(bytes, 0, if (leng == -1) 0 else leng)
            input.close()
            return temp
        }catch (e : IOException){
            e.printStackTrace()
        }finally {
            if(input != null){
                input.close()
            }
        }
        return ""
    }

    //获取CPU数值所在的位置
    private fun getCPUIndex(line : String) : Int{
        if(line.contains("CPU")){
            val titles = line.split("\\s+".toRegex())
            var index = 0
            for(str in titles){
                if(str.contains("CPU"))
                    return index
                index++
            }
        }
        return -1
    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195

Java版(目前只有获取CPU占用率和内存占用)

public static float getCPUUsage(){
        float rate = 0;
        Process process = null;
        try{
            process = Runtime.getRuntime().exec("top -n 1");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            int cpuIndex = -1;
            while((line = reader.readLine()) != null){
                line = line.trim();
                if(line == null){
                    continue;
                }
                int tempIndex = getCPUIndex(line);
                if(tempIndex != -1){
                    cpuIndex = tempIndex;
                    continue;
                }
                if(line.startsWith(android.os.Process.myPid()+"")){
                    if(cpuIndex == -1){
                        continue;
                    }
                    List<String> param = Arrays.asList(line.split("\\s+"));
                    if(param.size() <= cpuIndex){
                        continue;
                    }
                    String cpu = param.get(cpuIndex);
                    if(cpu.endsWith("%")){
                        cpu = cpu.substring(0, cpu.lastIndexOf("%"));
                    }
                    rate = Float.parseFloat(cpu) / Runtime.getRuntime().availableProcessors();
                    break;
                }
            }
        } catch (IOException e) {
            Log.d("ctb_e:",e.getMessage());
            e.printStackTrace();
        }finally {
            if (process != null){
                process.destroy();
            }
        }
        return  ((Math.round(rate*100))/100);
    }```

    private static int getCPUIndex(String line){
        if(line.contains("CPU")){
            List<String> list = Arrays.asList(line.split("\\s+"));
            for(int i = 0;i< list.size();i++){
                if(list.get(i).contains("CPU"))
                    return i;
            }
        }
        return -1;
    }

    /*
    单位:Kb
     */
    public static int getMemory(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        //最大分配内存
        int memory = activityManager.getMemoryClass();
        System.out.println("memory: "+memory);
        //最大分配内存获取方法
        float maxMemory = (float) (Runtime.getRuntime().maxMemory() * 1.0/ (1024 ));
        //当前分配的总内存
        float totalMemory = (float) (Runtime.getRuntime().totalMemory() * 1.0/ (1024));
        //剩余内存
        float freeMemory = (float) (Runtime.getRuntime().freeMemory() * 1.0/ (1024));
        return (int) (totalMemory-freeMemory);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/242316
推荐阅读
相关标签
  

闽ICP备14008679号