How can I check if an app running on Android?
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?
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
}
isInBackground
is the status of app
ActivityManager.RunningAppProcessInfo myProcess = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(myProcess);
Boolean isInBackground = myProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
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;
}