I have the solution.
public static boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
It works fine.
How I can to check that my application really in background? For example, I opened activity and started new Activity - standard Gallery (started from my application). This intent was started from my activity, and my application logically in foreground. I can check my activities, but how to check this situation too?
AND how can I check that the application was sent to the background FROM external activity (on this example - gallery)?
public boolean isApplicationSentToBackground(final Context context) {
Boolean flag = false;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= 23) {
List < ActivityManager.RunningTaskInfo > tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
flag = true;
}
}
} else {
try {
Thread.sleep(1500);
flag = false;
List < ActivityManager.RunningAppProcessInfo > runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo: runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
for (String activeProcess: processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
flag = true;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}