ActivityManager.getRunningTasks is deprecated android

蹲街弑〆低调 提交于 2019-11-27 07:40:00

This should help you get started

ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();

for (ActivityManager.AppTask task : tasks) {
    Log.d(TAG, "stackId: " + task.getTaskInfo().stackId);
}
Mihir Patel

This should work for the pre Lollipop devices as well as for Lollipop devices

public static boolean isBackgroundRunning(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        //If your app is the process in foreground, then it's not in running in background
                        return false;
                    }
                }
            }
        }


        return true;
    }

Edit: It should return true if the app is in background, not the opposite

May you want this:

/***
 * Checking Whether any Activity of Application is running or not
 * @param context
 * @return
 */
public static boolean isForeground(Context context) {

    // Get the Activity Manager
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

    // Get a list of running tasks, we are only interested in the last one,
    // the top most so we give a 1 as parameter so we only get the topmost.
    List<ActivityManager.RunningAppProcessInfo> task = manager.getRunningAppProcesses();

    // Get the info we need for comparison.
    ComponentName componentInfo = task.get(0).importanceReasonComponent;

    // Check if it matches our package name.
    if(componentInfo.getPackageName().equals(context.getPackageName()))
        return true;

    // If not then our app is not on the foreground.
    return false;
}

in Kotlin

fun isAppRunning(context: Context): Boolean {
  val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
  return activityManager.appTasks
    .filter { it.taskInfo != null }
    .filter { it.taskInfo.baseActivity != null }
    .any { it.taskInfo.baseActivity.packageName == context.packageName }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!