Certainly! Below is the updated complete Kotlin code for your Android Process Manager app. This version includes a new section that displays real-time graphs for CPU and memory performance, similar to the Windows Task Manager. The graphs are implemented using Jetpack Compose's Canvas for simplicity.
Key Additions:
- SystemStats Data Class: Represents system-wide CPU and memory usage.
- CpuMonitor Object: Handles reading CPU usage from
/proc/stat.
- MemoryMonitor Object: Utilizes
ActivityManager to retrieve memory usage.
- State Management: Maintains history lists for CPU and memory usage to plot the graphs.
- Composable Graphs: Custom composable functions
CpuGraph and MemoryGraph to render the usage graphs.
- UI Layout Update: Incorporates the graphs into the existing UI layout.
Complete Updated Code
package com.example.androidprocessmonitor
import android.app.ActivityManager
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.androidprocessmonitor.ui.theme.AndroidProcessMonitorTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.FileReader
import java.io.InputStreamReader
data class ProcessInfo(
val pid: String,
val name: String,
val cpuUsage: String,
val memoryUsage: String
)
data class SystemStats(
val cpuUsage: Float, // In percentage
val memoryUsage: Float // In percentage
)
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AndroidProcessMonitorTheme {
Surface {
ProcessMonitorScreen()
}
}
}
}
}
object CpuMonitor {
private var prevIdle: Long = 0
private var prevTotal: Long = 0
suspend fun getCpuUsage(): Float = withContext(Dispatchers.IO) {
try {
val reader = BufferedReader(FileReader("/proc/stat"))
val load = reader.readLine()
reader.close()
val toks = load.split(" +".toRegex()).drop(1)
val idle = toks[3].toLong()
val total = toks.map { it.toLong() }.sum()
val deltaIdle = idle - prevIdle
val deltaTotal = total - prevTotal
prevIdle = idle
prevTotal = total
if (deltaTotal == 0L) {
0f
} else {
((deltaTotal - deltaIdle) * 100f) / deltaTotal
}
} catch (e: Exception) {
e.printStackTrace()
0f
}
}
}
object MemoryMonitor {
suspend fun getMemoryUsage(context: Context): Float = withContext(Dispatchers.IO) {
try {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val memoryInfo = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(memoryInfo)
val totalMem = memoryInfo.totalMem
val availMem = memoryInfo.availMem
val usedMem = totalMem - availMem
(usedMem * 100f) / totalMem
} catch (e: Exception) {
e.printStackTrace()
0f
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProcessMonitorScreen() {
var processList by remember { mutableStateOf(emptyList<ProcessInfo>()) }
var searchQuery by remember { mutableStateOf("") }
val coroutineScope = rememberCoroutineScope()
// State for system stats
var cpuMemoryStats by remember { mutableStateOf(SystemStats(cpuUsage = 0f, memoryUsage = 0f)) }
// History lists for graphs
val cpuHistory = remember { mutableStateListOf<Float>() }
val memoryHistory = remember { mutableStateListOf<Float>() }
// Start the monitoring when this composable is first launched
LaunchedEffect(Unit) {
while (true) {
processList = getProcessList(context = it ?: return@LaunchedEffect)
delay(5000) // Update process list every 5 seconds
}
}
// Collect system stats every second
LaunchedEffect(Unit) {
while (true) {
val cpu = CpuMonitor.getCpuUsage()
val mem = MemoryMonitor.getMemoryUsage(context = LocalContext.current)
cpuMemoryStats = SystemStats(cpuUsage = cpu, memoryUsage = mem)
// Update history lists
cpuHistory.add(cpu)
memoryHistory.add(mem)
// Keep only the last 60 entries (e.g., last 60 seconds)
if (cpuHistory.size > 60) cpuHistory.removeAt(0)
if (memoryHistory.size > 60) memoryHistory.removeAt(0)
delay(1000) // Update every second
}
}
Scaffold(
topBar = {
TopAppBar(
title = { Text("Process Monitor", fontSize = 20.sp, fontWeight = FontWeight.Bold) }
)
}
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(16.dp)
) {
// Graph Section
Text(
text = "System Performance",
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(vertical = 8.dp)
)
Column(
modifier = Modifier
.fillMaxWidth()
.background(Color(0xFFF0F0F0), RoundedCornerShape(8.dp))
.padding(16.dp)
) {
Text(text = "CPU Usage: ${"%.2f".format(cpuMemoryStats.cpuUsage)}%", fontWeight = FontWeight.Medium)
Spacer(modifier = Modifier.height(4.dp))
CpuGraph(cpuHistory = cpuHistory)
Spacer(modifier = Modifier.height(16.dp))
Text(text = "Memory Usage: ${"%.2f".format(cpuMemoryStats.memoryUsage)}%", fontWeight = FontWeight.Medium)
Spacer(modifier = Modifier.height(4.dp))
MemoryGraph(memoryHistory = memoryHistory)
}
Spacer(modifier = Modifier.height(16.dp))
// Search Bar
SearchBar(searchQuery) { newQuery ->
searchQuery = newQuery
}
Spacer(modifier = Modifier.height(8.dp))
// Process List
ProcessList(
processList = processList.filter {
it.name.contains(searchQuery, ignoreCase = true)
},
onKillProcess = { pid ->
coroutineScope.launch {
killProcess(pid)
processList = processList.filter { it.pid != pid } // Remove killed process
}
}
)
}
}
}
@Composable
fun CpuGraph(cpuHistory: List<Float>) {
Canvas(modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.background(Color.White, RoundedCornerShape(4.dp))
) {
if (cpuHistory.isEmpty()) return@Canvas
val maxPoints = cpuHistory.size
val maxValue = 100f // CPU usage percentage
val pointGap = size.width / (60f) // Assuming max 60 points
// Draw background grid
drawLine(
color = Color.LightGray,
start = androidx.compose.ui.geometry.Offset(0f, size.height),
end = androidx.compose.ui.geometry.Offset(size.width, size.height),
strokeWidth = 2f
)
drawLine(
color = Color.LightGray,
start = androidx.compose.ui.geometry.Offset(0f, 0f),
end = androidx.compose.ui.geometry.Offset(0f, size.height),
strokeWidth = 2f
)
// Draw CPU usage line
val path = androidx.compose.ui.graphics.Path()
cpuHistory.forEachIndexed { index, value ->
val x = size.width - pointGap * (cpuHistory.size - index)
val y = size.height - (value / maxValue) * size.height
if (index == 0) {
path.moveTo(x, y)
} else {
path.lineTo(x, y)
}
}
drawPath(
path = path,
color = Color.Red,
style = androidx.compose.ui.graphics.drawscope.Stroke(width = 3f, cap = StrokeCap.Round)
)
}
}
@Composable
fun MemoryGraph(memoryHistory: List<Float>) {
Canvas(modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.background(Color.White, RoundedCornerShape(4.dp))
) {
if (memoryHistory.isEmpty()) return@Canvas
val maxPoints = memoryHistory.size
val maxValue = 100f // Memory usage percentage
val pointGap = size.width / (60f) // Assuming max 60 points
// Draw background grid
drawLine(
color = Color.LightGray,
start = androidx.compose.ui.geometry.Offset(0f, size.height),
end = androidx.compose.ui.geometry.Offset(size.width, size.height),
strokeWidth = 2f
)
drawLine(
color = Color.LightGray,
start = androidx.compose.ui.geometry.Offset(0f, 0f),
end = androidx.compose.ui.geometry.Offset(0f, size.height),
strokeWidth = 2f
)
// Draw Memory usage line
val path = androidx.compose.ui.graphics.Path()
memoryHistory.forEachIndexed { index, value ->
val x = size.width - pointGap * (memoryHistory.size - index)
val y = size.height - (value / maxValue) * size.height
if (index == 0) {
path.moveTo(x, y)
} else {
path.lineTo(x, y)
}
}
drawPath(
path = path,
color = Color.Blue,
style = androidx.compose.ui.graphics.drawscope.Stroke(width = 3f, cap = StrokeCap.Round)
)
}
}
@Composable
fun SearchBar(query: String, onQueryChange: (String) -> Unit) {
TextField(
value = query,
onValueChange = onQueryChange,
label = { Text("Search Processes") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.White
)
)
}
@Composable
fun ProcessList(processList: List<ProcessInfo>, onKillProcess: (String) -> Unit) {
if (processList.isEmpty()) {
Text("No processes found or root access denied.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(processList) { process ->
ProcessItem(process, onKillProcess)
Divider(color = Color.Gray, thickness = 1.dp)
}
}
}
}
@Composable
fun ProcessItem(process: ProcessInfo, onKillProcess: (String) -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
.background(Color(0xFFF0F0F0), RoundedCornerShape(8.dp))
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text(text = "PID: ${process.pid}", fontWeight = FontWeight.Bold, fontSize = 16.sp)
Text(text = process.name, fontSize = 14.sp)
Text(text = "CPU: ${process.cpuUsage}%", fontSize = 12.sp, color = Color.Gray)
Text(text = "Memory: ${process.memoryUsage}%", fontSize = 12.sp, color = Color.Gray)
}
Button(
onClick = { onKillProcess(process.pid) },
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red),
modifier = Modifier
.width(120.dp)
.height(40.dp)
) {
Text("Kill Process", color = Color.White, fontSize = 12.sp)
}
}
}
// Function to fetch the list of processes by executing a shell command
suspend fun getProcessList(context: Context): List<ProcessInfo> = withContext(Dispatchers.IO) {
val processList = mutableListOf<ProcessInfo>()
try {
// Using "ps -eo pid,comm,pcpu,pmem" to get PID, command, CPU%, and MEM%
val process = Runtime.getRuntime().exec("su -c ps -eo pid,comm,pcpu,pmem")
val reader = BufferedReader(InputStreamReader(process.inputStream))
reader.readLine() // Skip the header
reader.forEachLine { line ->
val columns = line.trim().split("\\s+".toRegex(), limit = 4)
if (columns.size == 4) {
val pid = columns[0]
val name = columns[1]
val cpuUsage = columns[2]
val memoryUsage = columns[3]
processList.add(ProcessInfo(pid, name, cpuUsage, memoryUsage))
}
}
reader.close()
} catch (e: Exception) {
e.printStackTrace()
}
processList
}
// Function to kill a process by PID using a root command
suspend fun killProcess(pid: String) = withContext(Dispatchers.IO) {
try {
Runtime.getRuntime().exec("su -c kill $pid")
} catch (e: Exception) {
e.printStackTrace()
}
}
Detailed Explanation of Additions
-
SystemStats Data Class
data class SystemStats(
val cpuUsage: Float, // In percentage
val memoryUsage: Float // In percentage
)
- Represents the current system CPU and memory usage.
-
CpuMonitor Object
object CpuMonitor {
private var prevIdle: Long = 0
private var prevTotal: Long = 0
suspend fun getCpuUsage(): Float = withContext(Dispatchers.IO) {
try {
val reader = BufferedReader(FileReader("/proc/stat"))
val load = reader.readLine()
reader.close()
val toks = load.split(" +".toRegex()).drop(1)
val idle = toks[3].toLong()
val total = toks.map { it.toLong() }.sum()
val deltaIdle = idle - prevIdle
val deltaTotal = total - prevTotal
prevIdle = idle
prevTotal = total
if (deltaTotal == 0L) {
0f
} else {
((deltaTotal - deltaIdle) * 100f) / deltaTotal
}
} catch (e: Exception) {
e.printStackTrace()
0f
}
}
}
- Reads
/proc/stat to calculate CPU usage.
- Computes the difference in idle and total CPU time between two consecutive reads to determine the usage percentage.
-
MemoryMonitor Object
object MemoryMonitor {
suspend fun getMemoryUsage(context: Context): Float = withContext(Dispatchers.IO) {
try {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val memoryInfo = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(memoryInfo)
val totalMem = memoryInfo.totalMem
val availMem = memoryInfo.availMem
val usedMem = totalMem - availMem
(usedMem * 100f) / totalMem
} catch (e: Exception) {
e.printStackTrace()
0f
}
}
}
- Uses
ActivityManager to fetch memory information.
- Calculates memory usage as a percentage.
-
State Management for System Stats and History Lists
// State for system stats
var cpuMemoryStats by remember { mutableStateOf(SystemStats(cpuUsage = 0f, memoryUsage = 0f)) }
// History lists for graphs
val cpuHistory = remember { mutableStateListOf<Float>() }
val memoryHistory = remember { mutableStateListOf<Float>() }
-
LaunchedEffect Blocks for Periodic Updates
// Start the monitoring when this composable is first launched
LaunchedEffect(Unit) {
while (true) {
processList = getProcessList(context = it ?: return@LaunchedEffect)
delay(5000) // Update process list every 5 seconds
}
}
// Collect system stats every second
LaunchedEffect(Unit) {
while (true) {
val cpu = CpuMonitor.getCpuUsage()
val mem = MemoryMonitor.getMemoryUsage(context = LocalContext.current)
cpuMemoryStats = SystemStats(cpuUsage = cpu, memoryUsage = mem)
// Update history lists
cpuHistory.add(cpu)
memoryHistory.add(mem)
// Keep only the last 60 entries (e.g., last 60 seconds)
if (cpuHistory.size > 60) cpuHistory.removeAt(0)
if (memoryHistory.size > 60) memoryHistory.removeAt(0)
delay(1000) // Update every second
}
}
Notes and Recommendations
-
Permissions:
- Reading
/proc/stat and executing su commands requires root access. Ensure that the device is rooted and that the app has the necessary permissions.
- Without root access, some functionalities, especially killing processes or reading certain system files, might not work.
-
Graph Performance:
- The current implementation uses
Canvas for drawing graphs, which is suitable for simple and lightweight graphs.
- For more advanced graph features, consider integrating a dedicated charting library compatible with Jetpack Compose, such as Compose Charts or Charts4Compose.
-
Optimizations:
- Data Sampling: Adjust the sampling rate based on performance needs. Currently, CPU and memory stats are sampled every second, and the process list every 5 seconds.
- Error Handling: Enhance error handling to inform users when certain functionalities fail, such as lacking root access.
-
UI Enhancements:
- Responsive Design: Ensure that the UI scales well across different screen sizes and orientations.
- Theming: Customize colors and styles to match the overall app theme and improve aesthetics.
-
Testing:
- Test the app on various devices to ensure compatibility, especially regarding access to system files and permissions.
- Monitor the app’s performance to ensure that the periodic readings and UI updates do not cause noticeable lag or increased battery consumption.
Conclusion
With these additions, your Android Process Manager now includes real-time CPU and memory usage graphs, enhancing its functionality to resemble the Windows Task Manager. Make sure to handle permissions appropriately and consider further optimizations and UI enhancements based on user feedback and testing.