How can I check if an app running on Android?

2019-01-02 14:42发布

I am an Android developer and I want to write an if statement in my application. In this statement I want to check if the default browser (browser in Android OS) is running. How can I do this programmatically?

2条回答
余欢
2楼-- · 2019-01-02 15:15

Add the below Helper class:

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;
        }
    }

Now you can check from the below code if your desired App is running or not:

if (Helper.isAppRunning(YourActivity.this, "com.your.desired.app")) {
    // App is running
} else {
    // App is not running
}
查看更多
萌妹纸的霸气范
3楼-- · 2019-01-02 15:40

You can check it by the following method

public static boolean isRunning(Context ctx) {
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);

    List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (ActivityManager.RunningTaskInfo task : tasks) {
        if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName()))
            return true;
    }
    return false;
}
查看更多
登录 后发表回答