Skip to content

Instantly share code, notes, and snippets.

@mahdi-malv
Created July 6, 2022 16:55
Show Gist options
  • Save mahdi-malv/648f6184690cc0ab8422b05bf4c043dc to your computer and use it in GitHub Desktop.
Save mahdi-malv/648f6184690cc0ab8422b05bf4c043dc to your computer and use it in GitHub Desktop.
static boolean isApplicationForeground(Context context) {
KeyguardManager keyguardManager =
(KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (keyguardManager != null && keyguardManager.isKeyguardLocked()) {
return false;
}
ActivityManager activityManager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (activityManager == null) return false;
List<ActivityManager.RunningAppProcessInfo> appProcesses =
activityManager.getRunningAppProcesses();
if (appProcesses == null) return false;
final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
&& appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment