I'm using a background service to repeatedly check after some interval whether my app is in foreground:
private int appForeInterval = 5000; // 5 secs
private Handler seenHandler;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
seenHandler = new Handler();
appForeChecker.run();
return Service.START_STICKY;
}
Runnable appForeChecker = new Runnable() {
@Override
public void run() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningProcInfo = activityManager.getRunningAppProcesses();
System.out.println(runningProcInfo.size()); // always prints 1
for(int i = 0; i < runningProcInfo.size(); i++){
System.out.println(runningProcInfo.get(i).processName); // only prints my package name in any case
if(runningProcInfo.get(i).processName.equals(my_app_package_name)) {
System.out.println(runningProcInfo.get(i).lru); // always prints 0 in any case
if (runningProcInfo.get(i).lru== ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
// this is never true 0 != 100
}
}
}
seenHandler.postDelayed(appForeChecker, appForeInterval);
}
};
Everytime, the runningProcInfo size is 1 and just my app's package name gets printed even though there are other apps in the background and even if my app is in the background. And lru is always 0. And this is for all cases, whether my app is in foreground or not.
How can I get correct results from this? The current app in foreground should be printed.