Posted on Leave a comment

Is android app in foreground

https://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not

[code language=”java”]
class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

@Override
protected Boolean doInBackground(Context… params) {
final Context context = params[0].getApplicationContext();
return isAppOnForeground(context);
}

private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}

// Use like this:
boolean foregroud = new ForegroundCheckTask().execute(context).get();
[/code]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.