How to Get CPU usage programmatically (With the cores frequency)
You should see this SO post here.
Basically, you want to use the RandomAccessFile
class to parse the /proc/stat
file.
EDIT: The above solution won't work for Android O and above. See this link for more information. The Reddit user fornwall filed a report to Google about this and got:
Status: Won't Fix (Intended Behavior) Thank you for filing this bug
report.The removal of /proc/stat was intentional. /proc/stat leaks side
channel information about applications which could allow one
application to infer the state of other applications on the device.
See
https://www.cl.cam.ac.uk/~lmrs2/publications/interrupts_pets16.pdf
for example.
EDIT2: I've prepared an example (not using CpuStasCollector)
package com.k3.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
private static int sLastCpuCoreCount = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.txtv);
textView.setText("");
for (int i = 0; i < calcCpuCoreCount(); i++) {
textView.append(takeCurrentCpuFreq(i) +"\n");
}
}
private static int readIntegerFile(String filePath) {
try {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(filePath)), 1000);
final String line = reader.readLine();
reader.close();
return Integer.parseInt(line);
} catch (Exception e) {
return 0;
}
}
private static int takeCurrentCpuFreq(int coreIndex) {
return readIntegerFile("/sys/devices/system/cpu/cpu" + coreIndex + "/cpufreq/scaling_cur_freq");
}
public static int calcCpuCoreCount() {
if (sLastCpuCoreCount >= 1) {
// キャッシュさせる
return sLastCpuCoreCount;
}
try {
// Get directory containing CPU info
final File dir = new File("/sys/devices/system/cpu/");
// Filter to only list the devices we care about
final File[] files = dir.listFiles(new FileFilter() {
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;
}
});
// Return the number of cores (virtual CPU devices)
sLastCpuCoreCount = files.length;
} catch(Exception e) {
sLastCpuCoreCount = Runtime.getRuntime().availableProcessors();
}
return sLastCpuCoreCount;
}
}
Get current cpu usage for each core on Android
The thread you have specified has only how to get the CPU Usage....If you read this answer carefully you can see there's method as "getCpuUsage". This method will return you the current CPU usage per each core once you pass the cpuid of the core.
How can I discover CPU usage of my application in Android (programmatically)?
I just found a way to calculate the CPU usage of a process by PID. According to the doc, the /proc/[pid]/stat
file contains status information about the process. So we can parse this file to get the following members:
- utime %lu
- stime %lu
Check this page to get more information about the /proc/[pid]/stat
file and the way to parse it.
Also here is a relevant question about utime
and stime
.
How do I read CPU stats in Java from an Android phone?
You can use the code in this answer: Get Memory Usage in Android
As mentioned in the comments, you can skip the first line to get per-core data.
Per comment below, you can read each line of the file and print the usages, and then split the lines as in the provided link:
public void printCpuUsages()
{
try
{
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
while (load != null)
{
Log.d("CPU", "CPU usage: " + load);
load = reader.readLine();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
Related Topics
Control the Playback Speed of Video in Android
How to Fix Mainactivity Does Not Have a Navcontroller
React Native | Failed to Install the App. Please Accept All Necessary Sdk Licenses Using Sdk Manager
How to Set Up Android Studio to Work Completely Offline
Refresh/Reload/Re Instantiate a Fragment in an Android Tab System
Adb.Exe Not Found After Installing Android Studio
How to Use Python to Execute Adb Commands
How to Painlessly Change My App Title Text Color
How to Make User Login from Only One Device At a Time
How to Set Align (Right or Left) of Text in Textview, Programmatically
How to Start an Activity from Background in Android 10
Suppress Keyboard from Popping Up
Method to Refresh Fragment Content When Data Changed ( Like Recall Oncreateview)
How to Set Spinner Default by Its Value Instead of Position
Android Prevent Immediate Trigger of Alarm Service If Alarm Time Has Passed For the Day
Java.Io.Ioexception: Permission Denied Cannot Create File
Android Q, Programmatically Connect to Different Wifi Ap for Internet