get list of current open apps in kotlin
import android.app.ActivityManager
import android.content.Context
fun getCurrentRunningApps(context: Context): List<String> {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val runningApps = mutableListOf<String>()
val runningProcesses = activityManager.runningAppProcesses ?: return emptyList()
for (processInfo in runningProcesses) {
runningApps.add(processInfo.processName)
}
return runningApps
}
Explanation:
import android.app.ActivityManager
: Import theActivityManager
class from the Android framework to manage the current state of applications.import android.content.Context
: Import theContext
class to access application-specific resources and classes.fun getCurrentRunningApps(context: Context): List<String>
: Define a function namedgetCurrentRunningApps
that takes aContext
parameter and returns a list of strings (representing app names).val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
: Retrieve the system service of typeACTIVITY_SERVICE
using the providedContext
and cast it to anActivityManager
object. This allows access to information about activities and processes on the device.val runningApps = mutableListOf<String>()
: Create an empty mutable list of strings to store the names of running apps.val runningProcesses = activityManager.runningAppProcesses ?: return emptyList()
: Retrieve the list of running application processes from theActivityManager
. If the list is null, return an empty list.for (processInfo in runningProcesses) { runningApps.add(processInfo.processName) }
: Iterate through the list of running processes obtained from theActivityManager
. Extract the process names and add them to therunningApps
list.return runningApps
: Return the list of running app names.
This Kotlin code snippet demonstrates how to use the ActivityManager
in Android to obtain a list of currently running apps by their process names.