I want to develop an app which can detect all the other apps are running in the background or not, not only my own app.

I did a lot search but almost all of them are detecting their own app, not all.

Any help will be really appreciated, thanks!

1 Answers

3
Nick On

Look at this method I created to get all running task:

private void getRunningApps() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    assert manager != null;
    if (android.os.Build.VERSION.SDK_INT <= 22) {
        List<ActivityManager.RunningTaskInfo> task = manager.getRunningTasks(5);
    } else {
        String mpackageName = manager.getRunningAppProcesses().get(0).processName;
        UsageStatsManager usage = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
        long time = System.currentTimeMillis();
        assert usage != null;
        List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, time);
        if (stats != null) {
            SortedMap<Long, UsageStats> runningTask = new TreeMap<>();
            for (UsageStats usageStats : stats) {
                runningTask.put(usageStats.getLastTimeUsed(), usageStats);
            }
        }
    }
}

You need permission get all tasks in manifest:

<uses-permission android:name="android.permission.GET_TASKS" />

And for dynamically checking permission for Android M or higher:

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean isAccessGranted() {
    try {
        PackageManager packageManager = getPackageManager();
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
        AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        int mode = 0;
        if (Globals.currentVersion > android.os.Build.VERSION_CODES.KITKAT) {
            assert appOpsManager != null;
            mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                    applicationInfo.uid, applicationInfo.packageName);
        }
        return (mode == AppOpsManager.MODE_ALLOWED);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}

And for asking permission. Here is:

Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivityForResult(intent, REQUEST_ACCESSBILITY);

Where REQUEST_ACCESSBILITY is int REQUEST_ACCESSBILITY = 100 use any number for request.