如何检查应用是否在安卓上运行?

2022-08-31 12:51:23

我是一名 Android 开发人员,我想在我的应用程序中编写一个语句。在此语句中,我想检查默认浏览器(Android OS中的浏览器)是否正在运行。如何以编程方式执行此操作?if


答案 1

添加以下帮助程序类:

public class Helper {

        public static boolean isAppRunning(final Context context, final String packageName) {
            final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            final List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
            if (procInfos != null)
            {
                for (final ActivityManager.RunningAppProcessInfo processInfo : procInfos) {
                    if (processInfo.processName.equals(packageName)) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

现在,您可以从下面的代码中检查所需的应用程序是否正在运行:

if (Helper.isAppRunning(YourActivity.this, "com.your.desired.app")) {
    // App is running
} else {
    // App is not running
}

答案 2

isInBackground是应用的状态

ActivityManager.RunningAppProcessInfo myProcess = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(myProcess);
Boolean isInBackground = myProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;

推荐