0

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.

user5155835
  • 4,392
  • 4
  • 53
  • 97

2 Answers2

0

Since you are working on latest version of android 5.1.1 and above you should use App usage for example explanation read below documentation.

The App usage statistics API allows app developers to collect statistics related to usage of the applications. This API provides more detailed usage information than the deprecated getRecentTasks() method.

This example illustrates how to use the App usage statistics API by showing the applications sorted by the timestamp of the last time each app was used.

To use this API, you must first declare the android.permission.PACKAGE_USAGE_STATS permission in your manifest. The user must also enable access for this app through Settings > Security > Apps with usage access.

To collect the statistics of the app usage, you need to first get the instance of UsageStatsManager by the following code:

mUsageStatsManager = (UsageStatsManager) getActivity()
       .getSystemService(Context.USAGE_STATS_SERVICE);

Then you can retrieve the statistics of the app usage by the following method:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
List<UsageStats> queryUsageStats = mUsageStatsManager
        .queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(),
                System.currentTimeMillis());

The first argument of the queryUsageStats() is used for the time interval by which the stats are aggregated. The second and the third arguments are used for specifying the beginning and the end of the range of the stats to include in the results

and also refer to this link

How to use UsageStatsManager?

also keep in mind getRunningAppProcesses will not work on all devices.

Community
  • 1
  • 1
Piyush
  • 1,973
  • 1
  • 19
  • 30
0

I solved using following method:

private boolean isForeground() {
    boolean isInForeground = false;
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(getPackageName())) {
                        isInForeground = true;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(getPackageName())) {
            isInForeground = true;
        }
    }

    return isInForeground;
}
user5155835
  • 4,392
  • 4
  • 53
  • 97
  • this will not work on 6.0 and 5.1.1 getRunningAppProcesses will not work. – Piyush Oct 15 '15 at 11:36
  • i am telling you it will not work on all the devices with 5.1.1 and 6.0 if you are happy with the solution then its but getRunningAppProcesses will not work – Piyush Oct 15 '15 at 11:38
  • ok because i also faced the same problem and if you are making an app restriction application like app lock you can see it doesnot work on moto x new with 5.1.1 unless you have given it app usage permission. – Piyush Oct 15 '15 at 11:41
  • I tested with Moto G 3rd generation, had to give 2 permissions: – user5155835 Oct 15 '15 at 11:43
  • ok if it fulfills your need but keep all devices in mind thanks. – Piyush Oct 15 '15 at 11:45
  • sure, also tested on an api 16 device – user5155835 Oct 15 '15 at 11:47