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:

  1. import android.app.ActivityManager: Import the ActivityManager class from the Android framework to manage the current state of applications.

  2. import android.content.Context: Import the Context class to access application-specific resources and classes.

  3. fun getCurrentRunningApps(context: Context): List<String>: Define a function named getCurrentRunningApps that takes a Context parameter and returns a list of strings (representing app names).

  4. val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager: Retrieve the system service of type ACTIVITY_SERVICE using the provided Context and cast it to an ActivityManager object. This allows access to information about activities and processes on the device.

  5. val runningApps = mutableListOf<String>(): Create an empty mutable list of strings to store the names of running apps.

  6. val runningProcesses = activityManager.runningAppProcesses ?: return emptyList(): Retrieve the list of running application processes from the ActivityManager. If the list is null, return an empty list.

  7. for (processInfo in runningProcesses) { runningApps.add(processInfo.processName) }: Iterate through the list of running processes obtained from the ActivityManager. Extract the process names and add them to the runningApps list.

  8. 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.