如何查看后台正在运行的应用程序

问题描述 投票:0回答:1

我有一个 Android 应用程序,比如说 A。 我只想检查应用程序 B 是否在后台运行。 如果不是,我想启动B应用程序。

这是我的代码:

private const val APPLICATION = "com.example.myapp"

class AppLauncher @Inject constructor(
    @ApplicationContext val context: Context
) {

    fun launchApplication() {
        when {
            !isInstalled() -> throw ApplicationNotInstalledException()
            !isAppRunning() -> launchApplicationB()
        }
    }

    private fun launchApplicationB() {
        val launchIntent: Intent? =
            context.packageManager.getLaunchIntentForPackage(APPLICATION)
        if (launchIntent != null) {
            context.startActivity(launchIntent)
        }
    }

    private fun isInstalled( ): Boolean {
        return try {
            context.packageManager.getPackageInfo(
                APPLICATION,
                PackageManager.GET_ACTIVITIES
            )
            true
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }


    private fun isAppRunning(): Boolean {
        val activityManager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager

        val runningProcesses = activityManager.runningAppProcesses
        for (process in runningProcesses) {
            if (process.processName == APPLICATION) {
                 return process.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND

            }
        }
        return false
    }
}

问题出在isAppRunning函数上:

 val runningProcesses = activityManager.runningAppProcesses

仅返回一个实例,即当前应用程序A的实例。

如何获取前台和后台所有正在运行的应用程序?

android kotlin background android-jetpack-compose
1个回答
0
投票

导入 android.app.ActivityManager 导入 android.content.Context

fun getRunningApps(context: Context): 列表 { val 活动管理器 = context.getSystemService(Context.ACTIVITY_SERVICE) 作为 ActivityManager val runningAppProcesses = ActivityManager.runningAppProcesses val runningApps = mutableListOf()

for (processInfo in runningAppProcesses) {
    runningApps.add(processInfo.processName)
}
return runningApps

}

© www.soinside.com 2019 - 2024. All rights reserved.