1. First add the GET_TASKS Manifest.permission to your AndroidManifest.xml
2. Use the below method to check if the app is in background or foreground
3. This method will return true if the app is in foreground.
JAVA :
protected Boolean isAppAtForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<activitymanager .runningtaskinfo=""> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : tasks) {
if (context.getPackageName().equals(tasks.get(0).topActivity.getPackageName()))
return true;
}
return false;
}
KOTLIN :
protected fun isAppAtForeground(context: Context): Boolean? {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val tasks = activityManager.getRunningTasks(Integer.MAX_VALUE)
for (task in tasks) {
if (context.getPackageName().equals(tasks[0].topActivity.packageName))
return true
}
return false
}
Comments
Post a Comment